diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/.coveragerc b/owl-bot-staging/google-analytics-admin/v1alpha/.coveragerc new file mode 100644 index 000000000000..9d9c116c67f8 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/analytics/admin/__init__.py + google/analytics/admin/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-analytics-admin/v1alpha/.flake8 b/owl-bot-staging/google-analytics-admin/v1alpha/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/.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-analytics-admin/v1alpha/MANIFEST.in b/owl-bot-staging/google-analytics-admin/v1alpha/MANIFEST.in new file mode 100644 index 000000000000..0377d1d1a750 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/analytics/admin *.py +recursive-include google/analytics/admin_v1alpha *.py diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/README.rst b/owl-bot-staging/google-analytics-admin/v1alpha/README.rst new file mode 100644 index 000000000000..890880fac92c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Analytics Admin 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 Analytics Admin 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-analytics-admin/v1alpha/docs/_static/custom.css b/owl-bot-staging/google-analytics-admin/v1alpha/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/docs/admin_v1alpha/analytics_admin_service.rst b/owl-bot-staging/google-analytics-admin/v1alpha/docs/admin_v1alpha/analytics_admin_service.rst new file mode 100644 index 000000000000..d771e00c9b42 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/docs/admin_v1alpha/analytics_admin_service.rst @@ -0,0 +1,10 @@ +AnalyticsAdminService +--------------------------------------- + +.. automodule:: google.analytics.admin_v1alpha.services.analytics_admin_service + :members: + :inherited-members: + +.. automodule:: google.analytics.admin_v1alpha.services.analytics_admin_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/docs/admin_v1alpha/services_.rst b/owl-bot-staging/google-analytics-admin/v1alpha/docs/admin_v1alpha/services_.rst new file mode 100644 index 000000000000..8d20fd9c0e52 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/docs/admin_v1alpha/services_.rst @@ -0,0 +1,6 @@ +Services for Google Analytics Admin v1alpha API +=============================================== +.. toctree:: + :maxdepth: 2 + + analytics_admin_service diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/docs/admin_v1alpha/types_.rst b/owl-bot-staging/google-analytics-admin/v1alpha/docs/admin_v1alpha/types_.rst new file mode 100644 index 000000000000..a9003712b4a9 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/docs/admin_v1alpha/types_.rst @@ -0,0 +1,6 @@ +Types for Google Analytics Admin v1alpha API +============================================ + +.. automodule:: google.analytics.admin_v1alpha.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/docs/conf.py b/owl-bot-staging/google-analytics-admin/v1alpha/docs/conf.py new file mode 100644 index 000000000000..184d93bfb9e6 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/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-analytics-admin 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-analytics-admin" +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 Analytics 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-analytics-admin-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-analytics-admin.tex", + u"google-analytics-admin 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-analytics-admin", + u"Google Analytics Admin 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-analytics-admin", + u"google-analytics-admin Documentation", + author, + "google-analytics-admin", + "GAPIC library for Google Analytics Admin 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-analytics-admin/v1alpha/docs/index.rst b/owl-bot-staging/google-analytics-admin/v1alpha/docs/index.rst new file mode 100644 index 000000000000..f2ac5cfeeaab --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + admin_v1alpha/services + admin_v1alpha/types diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin/__init__.py new file mode 100644 index 000000000000..b01cd173479b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin/__init__.py @@ -0,0 +1,595 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.analytics.admin_v1alpha.services.analytics_admin_service.client import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.services.analytics_admin_service.async_client import AnalyticsAdminServiceAsyncClient + +from google.analytics.admin_v1alpha.types.access_report import AccessBetweenFilter +from google.analytics.admin_v1alpha.types.access_report import AccessDateRange +from google.analytics.admin_v1alpha.types.access_report import AccessDimension +from google.analytics.admin_v1alpha.types.access_report import AccessDimensionHeader +from google.analytics.admin_v1alpha.types.access_report import AccessDimensionValue +from google.analytics.admin_v1alpha.types.access_report import AccessFilter +from google.analytics.admin_v1alpha.types.access_report import AccessFilterExpression +from google.analytics.admin_v1alpha.types.access_report import AccessFilterExpressionList +from google.analytics.admin_v1alpha.types.access_report import AccessInListFilter +from google.analytics.admin_v1alpha.types.access_report import AccessMetric +from google.analytics.admin_v1alpha.types.access_report import AccessMetricHeader +from google.analytics.admin_v1alpha.types.access_report import AccessMetricValue +from google.analytics.admin_v1alpha.types.access_report import AccessNumericFilter +from google.analytics.admin_v1alpha.types.access_report import AccessOrderBy +from google.analytics.admin_v1alpha.types.access_report import AccessQuota +from google.analytics.admin_v1alpha.types.access_report import AccessQuotaStatus +from google.analytics.admin_v1alpha.types.access_report import AccessRow +from google.analytics.admin_v1alpha.types.access_report import AccessStringFilter +from google.analytics.admin_v1alpha.types.access_report import NumericValue +from google.analytics.admin_v1alpha.types.analytics_admin import AcknowledgeUserDataCollectionRequest +from google.analytics.admin_v1alpha.types.analytics_admin import AcknowledgeUserDataCollectionResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ApproveDisplayVideo360AdvertiserLinkProposalRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ApproveDisplayVideo360AdvertiserLinkProposalResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ArchiveAudienceRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ArchiveCustomDimensionRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ArchiveCustomMetricRequest +from google.analytics.admin_v1alpha.types.analytics_admin import BatchCreateAccessBindingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import BatchCreateAccessBindingsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import BatchDeleteAccessBindingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import BatchGetAccessBindingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import BatchGetAccessBindingsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import BatchUpdateAccessBindingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import BatchUpdateAccessBindingsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import CancelDisplayVideo360AdvertiserLinkProposalRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateAccessBindingRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateAdSenseLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateAudienceRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateBigQueryLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateCalculatedMetricRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateChannelGroupRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateConnectedSiteTagRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateConnectedSiteTagResponse +from google.analytics.admin_v1alpha.types.analytics_admin import CreateConversionEventRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateCustomDimensionRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateCustomMetricRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateDataStreamRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateDisplayVideo360AdvertiserLinkProposalRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateDisplayVideo360AdvertiserLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateEventCreateRuleRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateEventEditRuleRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateExpandedDataSetRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateFirebaseLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateGoogleAdsLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateKeyEventRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateMeasurementProtocolSecretRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreatePropertyRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateRollupPropertyRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateRollupPropertyResponse +from google.analytics.admin_v1alpha.types.analytics_admin import CreateRollupPropertySourceLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateSearchAds360LinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateSKAdNetworkConversionValueSchemaRequest +from google.analytics.admin_v1alpha.types.analytics_admin import CreateSubpropertyEventFilterRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteAccessBindingRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteAccountRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteAdSenseLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteBigQueryLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteCalculatedMetricRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteChannelGroupRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteConnectedSiteTagRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteConversionEventRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteDataStreamRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteDisplayVideo360AdvertiserLinkProposalRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteDisplayVideo360AdvertiserLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteEventCreateRuleRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteEventEditRuleRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteExpandedDataSetRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteFirebaseLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteGoogleAdsLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteKeyEventRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteMeasurementProtocolSecretRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeletePropertyRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteRollupPropertySourceLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteSearchAds360LinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteSKAdNetworkConversionValueSchemaRequest +from google.analytics.admin_v1alpha.types.analytics_admin import DeleteSubpropertyEventFilterRequest +from google.analytics.admin_v1alpha.types.analytics_admin import FetchAutomatedGa4ConfigurationOptOutRequest +from google.analytics.admin_v1alpha.types.analytics_admin import FetchAutomatedGa4ConfigurationOptOutResponse +from google.analytics.admin_v1alpha.types.analytics_admin import FetchConnectedGa4PropertyRequest +from google.analytics.admin_v1alpha.types.analytics_admin import FetchConnectedGa4PropertyResponse +from google.analytics.admin_v1alpha.types.analytics_admin import GetAccessBindingRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetAccountRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetAdSenseLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetAttributionSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetAudienceRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetBigQueryLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetCalculatedMetricRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetChannelGroupRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetConversionEventRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetCustomDimensionRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetCustomMetricRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetDataRedactionSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetDataRetentionSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetDataSharingSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetDataStreamRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetDisplayVideo360AdvertiserLinkProposalRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetDisplayVideo360AdvertiserLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetEnhancedMeasurementSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetEventCreateRuleRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetEventEditRuleRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetExpandedDataSetRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetGlobalSiteTagRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetGoogleSignalsSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetKeyEventRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetMeasurementProtocolSecretRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetPropertyRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetRollupPropertySourceLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetSearchAds360LinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetSKAdNetworkConversionValueSchemaRequest +from google.analytics.admin_v1alpha.types.analytics_admin import GetSubpropertyEventFilterRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListAccessBindingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListAccessBindingsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListAccountsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListAccountsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListAccountSummariesRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListAccountSummariesResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListAdSenseLinksRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListAdSenseLinksResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListAudiencesRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListAudiencesResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListBigQueryLinksRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListBigQueryLinksResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListCalculatedMetricsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListCalculatedMetricsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListChannelGroupsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListChannelGroupsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListConnectedSiteTagsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListConnectedSiteTagsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListConversionEventsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListConversionEventsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListCustomDimensionsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListCustomDimensionsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListCustomMetricsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListCustomMetricsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListDataStreamsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListDataStreamsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListDisplayVideo360AdvertiserLinkProposalsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListDisplayVideo360AdvertiserLinkProposalsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListDisplayVideo360AdvertiserLinksRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListDisplayVideo360AdvertiserLinksResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListEventCreateRulesRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListEventCreateRulesResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListEventEditRulesRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListEventEditRulesResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListExpandedDataSetsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListExpandedDataSetsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListFirebaseLinksRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListFirebaseLinksResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListGoogleAdsLinksRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListGoogleAdsLinksResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListKeyEventsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListKeyEventsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListMeasurementProtocolSecretsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListMeasurementProtocolSecretsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListPropertiesRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListPropertiesResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListRollupPropertySourceLinksRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListRollupPropertySourceLinksResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListSearchAds360LinksRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListSearchAds360LinksResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListSKAdNetworkConversionValueSchemasRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListSKAdNetworkConversionValueSchemasResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ListSubpropertyEventFiltersRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ListSubpropertyEventFiltersResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ProvisionAccountTicketRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ProvisionAccountTicketResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ProvisionSubpropertyRequest +from google.analytics.admin_v1alpha.types.analytics_admin import ProvisionSubpropertyResponse +from google.analytics.admin_v1alpha.types.analytics_admin import ReorderEventEditRulesRequest +from google.analytics.admin_v1alpha.types.analytics_admin import RunAccessReportRequest +from google.analytics.admin_v1alpha.types.analytics_admin import RunAccessReportResponse +from google.analytics.admin_v1alpha.types.analytics_admin import SearchChangeHistoryEventsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import SearchChangeHistoryEventsResponse +from google.analytics.admin_v1alpha.types.analytics_admin import SetAutomatedGa4ConfigurationOptOutRequest +from google.analytics.admin_v1alpha.types.analytics_admin import SetAutomatedGa4ConfigurationOptOutResponse +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateAccessBindingRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateAccountRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateAttributionSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateAudienceRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateBigQueryLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateCalculatedMetricRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateChannelGroupRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateConversionEventRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateCustomDimensionRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateCustomMetricRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateDataRedactionSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateDataRetentionSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateDataStreamRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateDisplayVideo360AdvertiserLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateEnhancedMeasurementSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateEventCreateRuleRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateEventEditRuleRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateExpandedDataSetRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateGoogleAdsLinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateGoogleSignalsSettingsRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateKeyEventRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateMeasurementProtocolSecretRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdatePropertyRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateSearchAds360LinkRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateSKAdNetworkConversionValueSchemaRequest +from google.analytics.admin_v1alpha.types.analytics_admin import UpdateSubpropertyEventFilterRequest +from google.analytics.admin_v1alpha.types.audience import Audience +from google.analytics.admin_v1alpha.types.audience import AudienceDimensionOrMetricFilter +from google.analytics.admin_v1alpha.types.audience import AudienceEventFilter +from google.analytics.admin_v1alpha.types.audience import AudienceEventTrigger +from google.analytics.admin_v1alpha.types.audience import AudienceFilterClause +from google.analytics.admin_v1alpha.types.audience import AudienceFilterExpression +from google.analytics.admin_v1alpha.types.audience import AudienceFilterExpressionList +from google.analytics.admin_v1alpha.types.audience import AudienceSequenceFilter +from google.analytics.admin_v1alpha.types.audience import AudienceSimpleFilter +from google.analytics.admin_v1alpha.types.audience import AudienceFilterScope +from google.analytics.admin_v1alpha.types.channel_group import ChannelGroup +from google.analytics.admin_v1alpha.types.channel_group import ChannelGroupFilter +from google.analytics.admin_v1alpha.types.channel_group import ChannelGroupFilterExpression +from google.analytics.admin_v1alpha.types.channel_group import ChannelGroupFilterExpressionList +from google.analytics.admin_v1alpha.types.channel_group import GroupingRule +from google.analytics.admin_v1alpha.types.event_create_and_edit import EventCreateRule +from google.analytics.admin_v1alpha.types.event_create_and_edit import EventEditRule +from google.analytics.admin_v1alpha.types.event_create_and_edit import MatchingCondition +from google.analytics.admin_v1alpha.types.event_create_and_edit import ParameterMutation +from google.analytics.admin_v1alpha.types.expanded_data_set import ExpandedDataSet +from google.analytics.admin_v1alpha.types.expanded_data_set import ExpandedDataSetFilter +from google.analytics.admin_v1alpha.types.expanded_data_set import ExpandedDataSetFilterExpression +from google.analytics.admin_v1alpha.types.expanded_data_set import ExpandedDataSetFilterExpressionList +from google.analytics.admin_v1alpha.types.resources import AccessBinding +from google.analytics.admin_v1alpha.types.resources import Account +from google.analytics.admin_v1alpha.types.resources import AccountSummary +from google.analytics.admin_v1alpha.types.resources import AdSenseLink +from google.analytics.admin_v1alpha.types.resources import AttributionSettings +from google.analytics.admin_v1alpha.types.resources import BigQueryLink +from google.analytics.admin_v1alpha.types.resources import CalculatedMetric +from google.analytics.admin_v1alpha.types.resources import ChangeHistoryChange +from google.analytics.admin_v1alpha.types.resources import ChangeHistoryEvent +from google.analytics.admin_v1alpha.types.resources import ConnectedSiteTag +from google.analytics.admin_v1alpha.types.resources import ConversionEvent +from google.analytics.admin_v1alpha.types.resources import ConversionValues +from google.analytics.admin_v1alpha.types.resources import CustomDimension +from google.analytics.admin_v1alpha.types.resources import CustomMetric +from google.analytics.admin_v1alpha.types.resources import DataRedactionSettings +from google.analytics.admin_v1alpha.types.resources import DataRetentionSettings +from google.analytics.admin_v1alpha.types.resources import DataSharingSettings +from google.analytics.admin_v1alpha.types.resources import DataStream +from google.analytics.admin_v1alpha.types.resources import DisplayVideo360AdvertiserLink +from google.analytics.admin_v1alpha.types.resources import DisplayVideo360AdvertiserLinkProposal +from google.analytics.admin_v1alpha.types.resources import EnhancedMeasurementSettings +from google.analytics.admin_v1alpha.types.resources import EventMapping +from google.analytics.admin_v1alpha.types.resources import FirebaseLink +from google.analytics.admin_v1alpha.types.resources import GlobalSiteTag +from google.analytics.admin_v1alpha.types.resources import GoogleAdsLink +from google.analytics.admin_v1alpha.types.resources import GoogleSignalsSettings +from google.analytics.admin_v1alpha.types.resources import KeyEvent +from google.analytics.admin_v1alpha.types.resources import LinkProposalStatusDetails +from google.analytics.admin_v1alpha.types.resources import MeasurementProtocolSecret +from google.analytics.admin_v1alpha.types.resources import PostbackWindow +from google.analytics.admin_v1alpha.types.resources import Property +from google.analytics.admin_v1alpha.types.resources import PropertySummary +from google.analytics.admin_v1alpha.types.resources import RollupPropertySourceLink +from google.analytics.admin_v1alpha.types.resources import SearchAds360Link +from google.analytics.admin_v1alpha.types.resources import SKAdNetworkConversionValueSchema +from google.analytics.admin_v1alpha.types.resources import ActionType +from google.analytics.admin_v1alpha.types.resources import ActorType +from google.analytics.admin_v1alpha.types.resources import ChangeHistoryResourceType +from google.analytics.admin_v1alpha.types.resources import CoarseValue +from google.analytics.admin_v1alpha.types.resources import GoogleSignalsConsent +from google.analytics.admin_v1alpha.types.resources import GoogleSignalsState +from google.analytics.admin_v1alpha.types.resources import IndustryCategory +from google.analytics.admin_v1alpha.types.resources import LinkProposalInitiatingProduct +from google.analytics.admin_v1alpha.types.resources import LinkProposalState +from google.analytics.admin_v1alpha.types.resources import PropertyType +from google.analytics.admin_v1alpha.types.resources import ServiceLevel +from google.analytics.admin_v1alpha.types.subproperty_event_filter import SubpropertyEventFilter +from google.analytics.admin_v1alpha.types.subproperty_event_filter import SubpropertyEventFilterClause +from google.analytics.admin_v1alpha.types.subproperty_event_filter import SubpropertyEventFilterCondition +from google.analytics.admin_v1alpha.types.subproperty_event_filter import SubpropertyEventFilterExpression +from google.analytics.admin_v1alpha.types.subproperty_event_filter import SubpropertyEventFilterExpressionList + +__all__ = ('AnalyticsAdminServiceClient', + 'AnalyticsAdminServiceAsyncClient', + 'AccessBetweenFilter', + 'AccessDateRange', + 'AccessDimension', + 'AccessDimensionHeader', + 'AccessDimensionValue', + 'AccessFilter', + 'AccessFilterExpression', + 'AccessFilterExpressionList', + 'AccessInListFilter', + 'AccessMetric', + 'AccessMetricHeader', + 'AccessMetricValue', + 'AccessNumericFilter', + 'AccessOrderBy', + 'AccessQuota', + 'AccessQuotaStatus', + 'AccessRow', + 'AccessStringFilter', + 'NumericValue', + 'AcknowledgeUserDataCollectionRequest', + 'AcknowledgeUserDataCollectionResponse', + 'ApproveDisplayVideo360AdvertiserLinkProposalRequest', + 'ApproveDisplayVideo360AdvertiserLinkProposalResponse', + 'ArchiveAudienceRequest', + 'ArchiveCustomDimensionRequest', + 'ArchiveCustomMetricRequest', + 'BatchCreateAccessBindingsRequest', + 'BatchCreateAccessBindingsResponse', + 'BatchDeleteAccessBindingsRequest', + 'BatchGetAccessBindingsRequest', + 'BatchGetAccessBindingsResponse', + 'BatchUpdateAccessBindingsRequest', + 'BatchUpdateAccessBindingsResponse', + 'CancelDisplayVideo360AdvertiserLinkProposalRequest', + 'CreateAccessBindingRequest', + 'CreateAdSenseLinkRequest', + 'CreateAudienceRequest', + 'CreateBigQueryLinkRequest', + 'CreateCalculatedMetricRequest', + 'CreateChannelGroupRequest', + 'CreateConnectedSiteTagRequest', + 'CreateConnectedSiteTagResponse', + 'CreateConversionEventRequest', + 'CreateCustomDimensionRequest', + 'CreateCustomMetricRequest', + 'CreateDataStreamRequest', + 'CreateDisplayVideo360AdvertiserLinkProposalRequest', + 'CreateDisplayVideo360AdvertiserLinkRequest', + 'CreateEventCreateRuleRequest', + 'CreateEventEditRuleRequest', + 'CreateExpandedDataSetRequest', + 'CreateFirebaseLinkRequest', + 'CreateGoogleAdsLinkRequest', + 'CreateKeyEventRequest', + 'CreateMeasurementProtocolSecretRequest', + 'CreatePropertyRequest', + 'CreateRollupPropertyRequest', + 'CreateRollupPropertyResponse', + 'CreateRollupPropertySourceLinkRequest', + 'CreateSearchAds360LinkRequest', + 'CreateSKAdNetworkConversionValueSchemaRequest', + 'CreateSubpropertyEventFilterRequest', + 'DeleteAccessBindingRequest', + 'DeleteAccountRequest', + 'DeleteAdSenseLinkRequest', + 'DeleteBigQueryLinkRequest', + 'DeleteCalculatedMetricRequest', + 'DeleteChannelGroupRequest', + 'DeleteConnectedSiteTagRequest', + 'DeleteConversionEventRequest', + 'DeleteDataStreamRequest', + 'DeleteDisplayVideo360AdvertiserLinkProposalRequest', + 'DeleteDisplayVideo360AdvertiserLinkRequest', + 'DeleteEventCreateRuleRequest', + 'DeleteEventEditRuleRequest', + 'DeleteExpandedDataSetRequest', + 'DeleteFirebaseLinkRequest', + 'DeleteGoogleAdsLinkRequest', + 'DeleteKeyEventRequest', + 'DeleteMeasurementProtocolSecretRequest', + 'DeletePropertyRequest', + 'DeleteRollupPropertySourceLinkRequest', + 'DeleteSearchAds360LinkRequest', + 'DeleteSKAdNetworkConversionValueSchemaRequest', + 'DeleteSubpropertyEventFilterRequest', + 'FetchAutomatedGa4ConfigurationOptOutRequest', + 'FetchAutomatedGa4ConfigurationOptOutResponse', + 'FetchConnectedGa4PropertyRequest', + 'FetchConnectedGa4PropertyResponse', + 'GetAccessBindingRequest', + 'GetAccountRequest', + 'GetAdSenseLinkRequest', + 'GetAttributionSettingsRequest', + 'GetAudienceRequest', + 'GetBigQueryLinkRequest', + 'GetCalculatedMetricRequest', + 'GetChannelGroupRequest', + 'GetConversionEventRequest', + 'GetCustomDimensionRequest', + 'GetCustomMetricRequest', + 'GetDataRedactionSettingsRequest', + 'GetDataRetentionSettingsRequest', + 'GetDataSharingSettingsRequest', + 'GetDataStreamRequest', + 'GetDisplayVideo360AdvertiserLinkProposalRequest', + 'GetDisplayVideo360AdvertiserLinkRequest', + 'GetEnhancedMeasurementSettingsRequest', + 'GetEventCreateRuleRequest', + 'GetEventEditRuleRequest', + 'GetExpandedDataSetRequest', + 'GetGlobalSiteTagRequest', + 'GetGoogleSignalsSettingsRequest', + 'GetKeyEventRequest', + 'GetMeasurementProtocolSecretRequest', + 'GetPropertyRequest', + 'GetRollupPropertySourceLinkRequest', + 'GetSearchAds360LinkRequest', + 'GetSKAdNetworkConversionValueSchemaRequest', + 'GetSubpropertyEventFilterRequest', + 'ListAccessBindingsRequest', + 'ListAccessBindingsResponse', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListAccountSummariesRequest', + 'ListAccountSummariesResponse', + 'ListAdSenseLinksRequest', + 'ListAdSenseLinksResponse', + 'ListAudiencesRequest', + 'ListAudiencesResponse', + 'ListBigQueryLinksRequest', + 'ListBigQueryLinksResponse', + 'ListCalculatedMetricsRequest', + 'ListCalculatedMetricsResponse', + 'ListChannelGroupsRequest', + 'ListChannelGroupsResponse', + 'ListConnectedSiteTagsRequest', + 'ListConnectedSiteTagsResponse', + 'ListConversionEventsRequest', + 'ListConversionEventsResponse', + 'ListCustomDimensionsRequest', + 'ListCustomDimensionsResponse', + 'ListCustomMetricsRequest', + 'ListCustomMetricsResponse', + 'ListDataStreamsRequest', + 'ListDataStreamsResponse', + 'ListDisplayVideo360AdvertiserLinkProposalsRequest', + 'ListDisplayVideo360AdvertiserLinkProposalsResponse', + 'ListDisplayVideo360AdvertiserLinksRequest', + 'ListDisplayVideo360AdvertiserLinksResponse', + 'ListEventCreateRulesRequest', + 'ListEventCreateRulesResponse', + 'ListEventEditRulesRequest', + 'ListEventEditRulesResponse', + 'ListExpandedDataSetsRequest', + 'ListExpandedDataSetsResponse', + 'ListFirebaseLinksRequest', + 'ListFirebaseLinksResponse', + 'ListGoogleAdsLinksRequest', + 'ListGoogleAdsLinksResponse', + 'ListKeyEventsRequest', + 'ListKeyEventsResponse', + 'ListMeasurementProtocolSecretsRequest', + 'ListMeasurementProtocolSecretsResponse', + 'ListPropertiesRequest', + 'ListPropertiesResponse', + 'ListRollupPropertySourceLinksRequest', + 'ListRollupPropertySourceLinksResponse', + 'ListSearchAds360LinksRequest', + 'ListSearchAds360LinksResponse', + 'ListSKAdNetworkConversionValueSchemasRequest', + 'ListSKAdNetworkConversionValueSchemasResponse', + 'ListSubpropertyEventFiltersRequest', + 'ListSubpropertyEventFiltersResponse', + 'ProvisionAccountTicketRequest', + 'ProvisionAccountTicketResponse', + 'ProvisionSubpropertyRequest', + 'ProvisionSubpropertyResponse', + 'ReorderEventEditRulesRequest', + 'RunAccessReportRequest', + 'RunAccessReportResponse', + 'SearchChangeHistoryEventsRequest', + 'SearchChangeHistoryEventsResponse', + 'SetAutomatedGa4ConfigurationOptOutRequest', + 'SetAutomatedGa4ConfigurationOptOutResponse', + 'UpdateAccessBindingRequest', + 'UpdateAccountRequest', + 'UpdateAttributionSettingsRequest', + 'UpdateAudienceRequest', + 'UpdateBigQueryLinkRequest', + 'UpdateCalculatedMetricRequest', + 'UpdateChannelGroupRequest', + 'UpdateConversionEventRequest', + 'UpdateCustomDimensionRequest', + 'UpdateCustomMetricRequest', + 'UpdateDataRedactionSettingsRequest', + 'UpdateDataRetentionSettingsRequest', + 'UpdateDataStreamRequest', + 'UpdateDisplayVideo360AdvertiserLinkRequest', + 'UpdateEnhancedMeasurementSettingsRequest', + 'UpdateEventCreateRuleRequest', + 'UpdateEventEditRuleRequest', + 'UpdateExpandedDataSetRequest', + 'UpdateGoogleAdsLinkRequest', + 'UpdateGoogleSignalsSettingsRequest', + 'UpdateKeyEventRequest', + 'UpdateMeasurementProtocolSecretRequest', + 'UpdatePropertyRequest', + 'UpdateSearchAds360LinkRequest', + 'UpdateSKAdNetworkConversionValueSchemaRequest', + 'UpdateSubpropertyEventFilterRequest', + 'Audience', + 'AudienceDimensionOrMetricFilter', + 'AudienceEventFilter', + 'AudienceEventTrigger', + 'AudienceFilterClause', + 'AudienceFilterExpression', + 'AudienceFilterExpressionList', + 'AudienceSequenceFilter', + 'AudienceSimpleFilter', + 'AudienceFilterScope', + 'ChannelGroup', + 'ChannelGroupFilter', + 'ChannelGroupFilterExpression', + 'ChannelGroupFilterExpressionList', + 'GroupingRule', + 'EventCreateRule', + 'EventEditRule', + 'MatchingCondition', + 'ParameterMutation', + 'ExpandedDataSet', + 'ExpandedDataSetFilter', + 'ExpandedDataSetFilterExpression', + 'ExpandedDataSetFilterExpressionList', + 'AccessBinding', + 'Account', + 'AccountSummary', + 'AdSenseLink', + 'AttributionSettings', + 'BigQueryLink', + 'CalculatedMetric', + 'ChangeHistoryChange', + 'ChangeHistoryEvent', + 'ConnectedSiteTag', + 'ConversionEvent', + 'ConversionValues', + 'CustomDimension', + 'CustomMetric', + 'DataRedactionSettings', + 'DataRetentionSettings', + 'DataSharingSettings', + 'DataStream', + 'DisplayVideo360AdvertiserLink', + 'DisplayVideo360AdvertiserLinkProposal', + 'EnhancedMeasurementSettings', + 'EventMapping', + 'FirebaseLink', + 'GlobalSiteTag', + 'GoogleAdsLink', + 'GoogleSignalsSettings', + 'KeyEvent', + 'LinkProposalStatusDetails', + 'MeasurementProtocolSecret', + 'PostbackWindow', + 'Property', + 'PropertySummary', + 'RollupPropertySourceLink', + 'SearchAds360Link', + 'SKAdNetworkConversionValueSchema', + 'ActionType', + 'ActorType', + 'ChangeHistoryResourceType', + 'CoarseValue', + 'GoogleSignalsConsent', + 'GoogleSignalsState', + 'IndustryCategory', + 'LinkProposalInitiatingProduct', + 'LinkProposalState', + 'PropertyType', + 'ServiceLevel', + 'SubpropertyEventFilter', + 'SubpropertyEventFilterClause', + 'SubpropertyEventFilterCondition', + 'SubpropertyEventFilterExpression', + 'SubpropertyEventFilterExpressionList', +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin/gapic_version.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin/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-analytics-admin/v1alpha/google/analytics/admin/py.typed b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin/py.typed new file mode 100644 index 000000000000..3b7eb1470672 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-analytics-admin package uses inline types. diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/__init__.py new file mode 100644 index 000000000000..bb74d5cbe84d --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/__init__.py @@ -0,0 +1,596 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1alpha import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.analytics_admin_service import AnalyticsAdminServiceClient +from .services.analytics_admin_service import AnalyticsAdminServiceAsyncClient + +from .types.access_report import AccessBetweenFilter +from .types.access_report import AccessDateRange +from .types.access_report import AccessDimension +from .types.access_report import AccessDimensionHeader +from .types.access_report import AccessDimensionValue +from .types.access_report import AccessFilter +from .types.access_report import AccessFilterExpression +from .types.access_report import AccessFilterExpressionList +from .types.access_report import AccessInListFilter +from .types.access_report import AccessMetric +from .types.access_report import AccessMetricHeader +from .types.access_report import AccessMetricValue +from .types.access_report import AccessNumericFilter +from .types.access_report import AccessOrderBy +from .types.access_report import AccessQuota +from .types.access_report import AccessQuotaStatus +from .types.access_report import AccessRow +from .types.access_report import AccessStringFilter +from .types.access_report import NumericValue +from .types.analytics_admin import AcknowledgeUserDataCollectionRequest +from .types.analytics_admin import AcknowledgeUserDataCollectionResponse +from .types.analytics_admin import ApproveDisplayVideo360AdvertiserLinkProposalRequest +from .types.analytics_admin import ApproveDisplayVideo360AdvertiserLinkProposalResponse +from .types.analytics_admin import ArchiveAudienceRequest +from .types.analytics_admin import ArchiveCustomDimensionRequest +from .types.analytics_admin import ArchiveCustomMetricRequest +from .types.analytics_admin import BatchCreateAccessBindingsRequest +from .types.analytics_admin import BatchCreateAccessBindingsResponse +from .types.analytics_admin import BatchDeleteAccessBindingsRequest +from .types.analytics_admin import BatchGetAccessBindingsRequest +from .types.analytics_admin import BatchGetAccessBindingsResponse +from .types.analytics_admin import BatchUpdateAccessBindingsRequest +from .types.analytics_admin import BatchUpdateAccessBindingsResponse +from .types.analytics_admin import CancelDisplayVideo360AdvertiserLinkProposalRequest +from .types.analytics_admin import CreateAccessBindingRequest +from .types.analytics_admin import CreateAdSenseLinkRequest +from .types.analytics_admin import CreateAudienceRequest +from .types.analytics_admin import CreateBigQueryLinkRequest +from .types.analytics_admin import CreateCalculatedMetricRequest +from .types.analytics_admin import CreateChannelGroupRequest +from .types.analytics_admin import CreateConnectedSiteTagRequest +from .types.analytics_admin import CreateConnectedSiteTagResponse +from .types.analytics_admin import CreateConversionEventRequest +from .types.analytics_admin import CreateCustomDimensionRequest +from .types.analytics_admin import CreateCustomMetricRequest +from .types.analytics_admin import CreateDataStreamRequest +from .types.analytics_admin import CreateDisplayVideo360AdvertiserLinkProposalRequest +from .types.analytics_admin import CreateDisplayVideo360AdvertiserLinkRequest +from .types.analytics_admin import CreateEventCreateRuleRequest +from .types.analytics_admin import CreateEventEditRuleRequest +from .types.analytics_admin import CreateExpandedDataSetRequest +from .types.analytics_admin import CreateFirebaseLinkRequest +from .types.analytics_admin import CreateGoogleAdsLinkRequest +from .types.analytics_admin import CreateKeyEventRequest +from .types.analytics_admin import CreateMeasurementProtocolSecretRequest +from .types.analytics_admin import CreatePropertyRequest +from .types.analytics_admin import CreateRollupPropertyRequest +from .types.analytics_admin import CreateRollupPropertyResponse +from .types.analytics_admin import CreateRollupPropertySourceLinkRequest +from .types.analytics_admin import CreateSearchAds360LinkRequest +from .types.analytics_admin import CreateSKAdNetworkConversionValueSchemaRequest +from .types.analytics_admin import CreateSubpropertyEventFilterRequest +from .types.analytics_admin import DeleteAccessBindingRequest +from .types.analytics_admin import DeleteAccountRequest +from .types.analytics_admin import DeleteAdSenseLinkRequest +from .types.analytics_admin import DeleteBigQueryLinkRequest +from .types.analytics_admin import DeleteCalculatedMetricRequest +from .types.analytics_admin import DeleteChannelGroupRequest +from .types.analytics_admin import DeleteConnectedSiteTagRequest +from .types.analytics_admin import DeleteConversionEventRequest +from .types.analytics_admin import DeleteDataStreamRequest +from .types.analytics_admin import DeleteDisplayVideo360AdvertiserLinkProposalRequest +from .types.analytics_admin import DeleteDisplayVideo360AdvertiserLinkRequest +from .types.analytics_admin import DeleteEventCreateRuleRequest +from .types.analytics_admin import DeleteEventEditRuleRequest +from .types.analytics_admin import DeleteExpandedDataSetRequest +from .types.analytics_admin import DeleteFirebaseLinkRequest +from .types.analytics_admin import DeleteGoogleAdsLinkRequest +from .types.analytics_admin import DeleteKeyEventRequest +from .types.analytics_admin import DeleteMeasurementProtocolSecretRequest +from .types.analytics_admin import DeletePropertyRequest +from .types.analytics_admin import DeleteRollupPropertySourceLinkRequest +from .types.analytics_admin import DeleteSearchAds360LinkRequest +from .types.analytics_admin import DeleteSKAdNetworkConversionValueSchemaRequest +from .types.analytics_admin import DeleteSubpropertyEventFilterRequest +from .types.analytics_admin import FetchAutomatedGa4ConfigurationOptOutRequest +from .types.analytics_admin import FetchAutomatedGa4ConfigurationOptOutResponse +from .types.analytics_admin import FetchConnectedGa4PropertyRequest +from .types.analytics_admin import FetchConnectedGa4PropertyResponse +from .types.analytics_admin import GetAccessBindingRequest +from .types.analytics_admin import GetAccountRequest +from .types.analytics_admin import GetAdSenseLinkRequest +from .types.analytics_admin import GetAttributionSettingsRequest +from .types.analytics_admin import GetAudienceRequest +from .types.analytics_admin import GetBigQueryLinkRequest +from .types.analytics_admin import GetCalculatedMetricRequest +from .types.analytics_admin import GetChannelGroupRequest +from .types.analytics_admin import GetConversionEventRequest +from .types.analytics_admin import GetCustomDimensionRequest +from .types.analytics_admin import GetCustomMetricRequest +from .types.analytics_admin import GetDataRedactionSettingsRequest +from .types.analytics_admin import GetDataRetentionSettingsRequest +from .types.analytics_admin import GetDataSharingSettingsRequest +from .types.analytics_admin import GetDataStreamRequest +from .types.analytics_admin import GetDisplayVideo360AdvertiserLinkProposalRequest +from .types.analytics_admin import GetDisplayVideo360AdvertiserLinkRequest +from .types.analytics_admin import GetEnhancedMeasurementSettingsRequest +from .types.analytics_admin import GetEventCreateRuleRequest +from .types.analytics_admin import GetEventEditRuleRequest +from .types.analytics_admin import GetExpandedDataSetRequest +from .types.analytics_admin import GetGlobalSiteTagRequest +from .types.analytics_admin import GetGoogleSignalsSettingsRequest +from .types.analytics_admin import GetKeyEventRequest +from .types.analytics_admin import GetMeasurementProtocolSecretRequest +from .types.analytics_admin import GetPropertyRequest +from .types.analytics_admin import GetRollupPropertySourceLinkRequest +from .types.analytics_admin import GetSearchAds360LinkRequest +from .types.analytics_admin import GetSKAdNetworkConversionValueSchemaRequest +from .types.analytics_admin import GetSubpropertyEventFilterRequest +from .types.analytics_admin import ListAccessBindingsRequest +from .types.analytics_admin import ListAccessBindingsResponse +from .types.analytics_admin import ListAccountsRequest +from .types.analytics_admin import ListAccountsResponse +from .types.analytics_admin import ListAccountSummariesRequest +from .types.analytics_admin import ListAccountSummariesResponse +from .types.analytics_admin import ListAdSenseLinksRequest +from .types.analytics_admin import ListAdSenseLinksResponse +from .types.analytics_admin import ListAudiencesRequest +from .types.analytics_admin import ListAudiencesResponse +from .types.analytics_admin import ListBigQueryLinksRequest +from .types.analytics_admin import ListBigQueryLinksResponse +from .types.analytics_admin import ListCalculatedMetricsRequest +from .types.analytics_admin import ListCalculatedMetricsResponse +from .types.analytics_admin import ListChannelGroupsRequest +from .types.analytics_admin import ListChannelGroupsResponse +from .types.analytics_admin import ListConnectedSiteTagsRequest +from .types.analytics_admin import ListConnectedSiteTagsResponse +from .types.analytics_admin import ListConversionEventsRequest +from .types.analytics_admin import ListConversionEventsResponse +from .types.analytics_admin import ListCustomDimensionsRequest +from .types.analytics_admin import ListCustomDimensionsResponse +from .types.analytics_admin import ListCustomMetricsRequest +from .types.analytics_admin import ListCustomMetricsResponse +from .types.analytics_admin import ListDataStreamsRequest +from .types.analytics_admin import ListDataStreamsResponse +from .types.analytics_admin import ListDisplayVideo360AdvertiserLinkProposalsRequest +from .types.analytics_admin import ListDisplayVideo360AdvertiserLinkProposalsResponse +from .types.analytics_admin import ListDisplayVideo360AdvertiserLinksRequest +from .types.analytics_admin import ListDisplayVideo360AdvertiserLinksResponse +from .types.analytics_admin import ListEventCreateRulesRequest +from .types.analytics_admin import ListEventCreateRulesResponse +from .types.analytics_admin import ListEventEditRulesRequest +from .types.analytics_admin import ListEventEditRulesResponse +from .types.analytics_admin import ListExpandedDataSetsRequest +from .types.analytics_admin import ListExpandedDataSetsResponse +from .types.analytics_admin import ListFirebaseLinksRequest +from .types.analytics_admin import ListFirebaseLinksResponse +from .types.analytics_admin import ListGoogleAdsLinksRequest +from .types.analytics_admin import ListGoogleAdsLinksResponse +from .types.analytics_admin import ListKeyEventsRequest +from .types.analytics_admin import ListKeyEventsResponse +from .types.analytics_admin import ListMeasurementProtocolSecretsRequest +from .types.analytics_admin import ListMeasurementProtocolSecretsResponse +from .types.analytics_admin import ListPropertiesRequest +from .types.analytics_admin import ListPropertiesResponse +from .types.analytics_admin import ListRollupPropertySourceLinksRequest +from .types.analytics_admin import ListRollupPropertySourceLinksResponse +from .types.analytics_admin import ListSearchAds360LinksRequest +from .types.analytics_admin import ListSearchAds360LinksResponse +from .types.analytics_admin import ListSKAdNetworkConversionValueSchemasRequest +from .types.analytics_admin import ListSKAdNetworkConversionValueSchemasResponse +from .types.analytics_admin import ListSubpropertyEventFiltersRequest +from .types.analytics_admin import ListSubpropertyEventFiltersResponse +from .types.analytics_admin import ProvisionAccountTicketRequest +from .types.analytics_admin import ProvisionAccountTicketResponse +from .types.analytics_admin import ProvisionSubpropertyRequest +from .types.analytics_admin import ProvisionSubpropertyResponse +from .types.analytics_admin import ReorderEventEditRulesRequest +from .types.analytics_admin import RunAccessReportRequest +from .types.analytics_admin import RunAccessReportResponse +from .types.analytics_admin import SearchChangeHistoryEventsRequest +from .types.analytics_admin import SearchChangeHistoryEventsResponse +from .types.analytics_admin import SetAutomatedGa4ConfigurationOptOutRequest +from .types.analytics_admin import SetAutomatedGa4ConfigurationOptOutResponse +from .types.analytics_admin import UpdateAccessBindingRequest +from .types.analytics_admin import UpdateAccountRequest +from .types.analytics_admin import UpdateAttributionSettingsRequest +from .types.analytics_admin import UpdateAudienceRequest +from .types.analytics_admin import UpdateBigQueryLinkRequest +from .types.analytics_admin import UpdateCalculatedMetricRequest +from .types.analytics_admin import UpdateChannelGroupRequest +from .types.analytics_admin import UpdateConversionEventRequest +from .types.analytics_admin import UpdateCustomDimensionRequest +from .types.analytics_admin import UpdateCustomMetricRequest +from .types.analytics_admin import UpdateDataRedactionSettingsRequest +from .types.analytics_admin import UpdateDataRetentionSettingsRequest +from .types.analytics_admin import UpdateDataStreamRequest +from .types.analytics_admin import UpdateDisplayVideo360AdvertiserLinkRequest +from .types.analytics_admin import UpdateEnhancedMeasurementSettingsRequest +from .types.analytics_admin import UpdateEventCreateRuleRequest +from .types.analytics_admin import UpdateEventEditRuleRequest +from .types.analytics_admin import UpdateExpandedDataSetRequest +from .types.analytics_admin import UpdateGoogleAdsLinkRequest +from .types.analytics_admin import UpdateGoogleSignalsSettingsRequest +from .types.analytics_admin import UpdateKeyEventRequest +from .types.analytics_admin import UpdateMeasurementProtocolSecretRequest +from .types.analytics_admin import UpdatePropertyRequest +from .types.analytics_admin import UpdateSearchAds360LinkRequest +from .types.analytics_admin import UpdateSKAdNetworkConversionValueSchemaRequest +from .types.analytics_admin import UpdateSubpropertyEventFilterRequest +from .types.audience import Audience +from .types.audience import AudienceDimensionOrMetricFilter +from .types.audience import AudienceEventFilter +from .types.audience import AudienceEventTrigger +from .types.audience import AudienceFilterClause +from .types.audience import AudienceFilterExpression +from .types.audience import AudienceFilterExpressionList +from .types.audience import AudienceSequenceFilter +from .types.audience import AudienceSimpleFilter +from .types.audience import AudienceFilterScope +from .types.channel_group import ChannelGroup +from .types.channel_group import ChannelGroupFilter +from .types.channel_group import ChannelGroupFilterExpression +from .types.channel_group import ChannelGroupFilterExpressionList +from .types.channel_group import GroupingRule +from .types.event_create_and_edit import EventCreateRule +from .types.event_create_and_edit import EventEditRule +from .types.event_create_and_edit import MatchingCondition +from .types.event_create_and_edit import ParameterMutation +from .types.expanded_data_set import ExpandedDataSet +from .types.expanded_data_set import ExpandedDataSetFilter +from .types.expanded_data_set import ExpandedDataSetFilterExpression +from .types.expanded_data_set import ExpandedDataSetFilterExpressionList +from .types.resources import AccessBinding +from .types.resources import Account +from .types.resources import AccountSummary +from .types.resources import AdSenseLink +from .types.resources import AttributionSettings +from .types.resources import BigQueryLink +from .types.resources import CalculatedMetric +from .types.resources import ChangeHistoryChange +from .types.resources import ChangeHistoryEvent +from .types.resources import ConnectedSiteTag +from .types.resources import ConversionEvent +from .types.resources import ConversionValues +from .types.resources import CustomDimension +from .types.resources import CustomMetric +from .types.resources import DataRedactionSettings +from .types.resources import DataRetentionSettings +from .types.resources import DataSharingSettings +from .types.resources import DataStream +from .types.resources import DisplayVideo360AdvertiserLink +from .types.resources import DisplayVideo360AdvertiserLinkProposal +from .types.resources import EnhancedMeasurementSettings +from .types.resources import EventMapping +from .types.resources import FirebaseLink +from .types.resources import GlobalSiteTag +from .types.resources import GoogleAdsLink +from .types.resources import GoogleSignalsSettings +from .types.resources import KeyEvent +from .types.resources import LinkProposalStatusDetails +from .types.resources import MeasurementProtocolSecret +from .types.resources import PostbackWindow +from .types.resources import Property +from .types.resources import PropertySummary +from .types.resources import RollupPropertySourceLink +from .types.resources import SearchAds360Link +from .types.resources import SKAdNetworkConversionValueSchema +from .types.resources import ActionType +from .types.resources import ActorType +from .types.resources import ChangeHistoryResourceType +from .types.resources import CoarseValue +from .types.resources import GoogleSignalsConsent +from .types.resources import GoogleSignalsState +from .types.resources import IndustryCategory +from .types.resources import LinkProposalInitiatingProduct +from .types.resources import LinkProposalState +from .types.resources import PropertyType +from .types.resources import ServiceLevel +from .types.subproperty_event_filter import SubpropertyEventFilter +from .types.subproperty_event_filter import SubpropertyEventFilterClause +from .types.subproperty_event_filter import SubpropertyEventFilterCondition +from .types.subproperty_event_filter import SubpropertyEventFilterExpression +from .types.subproperty_event_filter import SubpropertyEventFilterExpressionList + +__all__ = ( + 'AnalyticsAdminServiceAsyncClient', +'AccessBetweenFilter', +'AccessBinding', +'AccessDateRange', +'AccessDimension', +'AccessDimensionHeader', +'AccessDimensionValue', +'AccessFilter', +'AccessFilterExpression', +'AccessFilterExpressionList', +'AccessInListFilter', +'AccessMetric', +'AccessMetricHeader', +'AccessMetricValue', +'AccessNumericFilter', +'AccessOrderBy', +'AccessQuota', +'AccessQuotaStatus', +'AccessRow', +'AccessStringFilter', +'Account', +'AccountSummary', +'AcknowledgeUserDataCollectionRequest', +'AcknowledgeUserDataCollectionResponse', +'ActionType', +'ActorType', +'AdSenseLink', +'AnalyticsAdminServiceClient', +'ApproveDisplayVideo360AdvertiserLinkProposalRequest', +'ApproveDisplayVideo360AdvertiserLinkProposalResponse', +'ArchiveAudienceRequest', +'ArchiveCustomDimensionRequest', +'ArchiveCustomMetricRequest', +'AttributionSettings', +'Audience', +'AudienceDimensionOrMetricFilter', +'AudienceEventFilter', +'AudienceEventTrigger', +'AudienceFilterClause', +'AudienceFilterExpression', +'AudienceFilterExpressionList', +'AudienceFilterScope', +'AudienceSequenceFilter', +'AudienceSimpleFilter', +'BatchCreateAccessBindingsRequest', +'BatchCreateAccessBindingsResponse', +'BatchDeleteAccessBindingsRequest', +'BatchGetAccessBindingsRequest', +'BatchGetAccessBindingsResponse', +'BatchUpdateAccessBindingsRequest', +'BatchUpdateAccessBindingsResponse', +'BigQueryLink', +'CalculatedMetric', +'CancelDisplayVideo360AdvertiserLinkProposalRequest', +'ChangeHistoryChange', +'ChangeHistoryEvent', +'ChangeHistoryResourceType', +'ChannelGroup', +'ChannelGroupFilter', +'ChannelGroupFilterExpression', +'ChannelGroupFilterExpressionList', +'CoarseValue', +'ConnectedSiteTag', +'ConversionEvent', +'ConversionValues', +'CreateAccessBindingRequest', +'CreateAdSenseLinkRequest', +'CreateAudienceRequest', +'CreateBigQueryLinkRequest', +'CreateCalculatedMetricRequest', +'CreateChannelGroupRequest', +'CreateConnectedSiteTagRequest', +'CreateConnectedSiteTagResponse', +'CreateConversionEventRequest', +'CreateCustomDimensionRequest', +'CreateCustomMetricRequest', +'CreateDataStreamRequest', +'CreateDisplayVideo360AdvertiserLinkProposalRequest', +'CreateDisplayVideo360AdvertiserLinkRequest', +'CreateEventCreateRuleRequest', +'CreateEventEditRuleRequest', +'CreateExpandedDataSetRequest', +'CreateFirebaseLinkRequest', +'CreateGoogleAdsLinkRequest', +'CreateKeyEventRequest', +'CreateMeasurementProtocolSecretRequest', +'CreatePropertyRequest', +'CreateRollupPropertyRequest', +'CreateRollupPropertyResponse', +'CreateRollupPropertySourceLinkRequest', +'CreateSKAdNetworkConversionValueSchemaRequest', +'CreateSearchAds360LinkRequest', +'CreateSubpropertyEventFilterRequest', +'CustomDimension', +'CustomMetric', +'DataRedactionSettings', +'DataRetentionSettings', +'DataSharingSettings', +'DataStream', +'DeleteAccessBindingRequest', +'DeleteAccountRequest', +'DeleteAdSenseLinkRequest', +'DeleteBigQueryLinkRequest', +'DeleteCalculatedMetricRequest', +'DeleteChannelGroupRequest', +'DeleteConnectedSiteTagRequest', +'DeleteConversionEventRequest', +'DeleteDataStreamRequest', +'DeleteDisplayVideo360AdvertiserLinkProposalRequest', +'DeleteDisplayVideo360AdvertiserLinkRequest', +'DeleteEventCreateRuleRequest', +'DeleteEventEditRuleRequest', +'DeleteExpandedDataSetRequest', +'DeleteFirebaseLinkRequest', +'DeleteGoogleAdsLinkRequest', +'DeleteKeyEventRequest', +'DeleteMeasurementProtocolSecretRequest', +'DeletePropertyRequest', +'DeleteRollupPropertySourceLinkRequest', +'DeleteSKAdNetworkConversionValueSchemaRequest', +'DeleteSearchAds360LinkRequest', +'DeleteSubpropertyEventFilterRequest', +'DisplayVideo360AdvertiserLink', +'DisplayVideo360AdvertiserLinkProposal', +'EnhancedMeasurementSettings', +'EventCreateRule', +'EventEditRule', +'EventMapping', +'ExpandedDataSet', +'ExpandedDataSetFilter', +'ExpandedDataSetFilterExpression', +'ExpandedDataSetFilterExpressionList', +'FetchAutomatedGa4ConfigurationOptOutRequest', +'FetchAutomatedGa4ConfigurationOptOutResponse', +'FetchConnectedGa4PropertyRequest', +'FetchConnectedGa4PropertyResponse', +'FirebaseLink', +'GetAccessBindingRequest', +'GetAccountRequest', +'GetAdSenseLinkRequest', +'GetAttributionSettingsRequest', +'GetAudienceRequest', +'GetBigQueryLinkRequest', +'GetCalculatedMetricRequest', +'GetChannelGroupRequest', +'GetConversionEventRequest', +'GetCustomDimensionRequest', +'GetCustomMetricRequest', +'GetDataRedactionSettingsRequest', +'GetDataRetentionSettingsRequest', +'GetDataSharingSettingsRequest', +'GetDataStreamRequest', +'GetDisplayVideo360AdvertiserLinkProposalRequest', +'GetDisplayVideo360AdvertiserLinkRequest', +'GetEnhancedMeasurementSettingsRequest', +'GetEventCreateRuleRequest', +'GetEventEditRuleRequest', +'GetExpandedDataSetRequest', +'GetGlobalSiteTagRequest', +'GetGoogleSignalsSettingsRequest', +'GetKeyEventRequest', +'GetMeasurementProtocolSecretRequest', +'GetPropertyRequest', +'GetRollupPropertySourceLinkRequest', +'GetSKAdNetworkConversionValueSchemaRequest', +'GetSearchAds360LinkRequest', +'GetSubpropertyEventFilterRequest', +'GlobalSiteTag', +'GoogleAdsLink', +'GoogleSignalsConsent', +'GoogleSignalsSettings', +'GoogleSignalsState', +'GroupingRule', +'IndustryCategory', +'KeyEvent', +'LinkProposalInitiatingProduct', +'LinkProposalState', +'LinkProposalStatusDetails', +'ListAccessBindingsRequest', +'ListAccessBindingsResponse', +'ListAccountSummariesRequest', +'ListAccountSummariesResponse', +'ListAccountsRequest', +'ListAccountsResponse', +'ListAdSenseLinksRequest', +'ListAdSenseLinksResponse', +'ListAudiencesRequest', +'ListAudiencesResponse', +'ListBigQueryLinksRequest', +'ListBigQueryLinksResponse', +'ListCalculatedMetricsRequest', +'ListCalculatedMetricsResponse', +'ListChannelGroupsRequest', +'ListChannelGroupsResponse', +'ListConnectedSiteTagsRequest', +'ListConnectedSiteTagsResponse', +'ListConversionEventsRequest', +'ListConversionEventsResponse', +'ListCustomDimensionsRequest', +'ListCustomDimensionsResponse', +'ListCustomMetricsRequest', +'ListCustomMetricsResponse', +'ListDataStreamsRequest', +'ListDataStreamsResponse', +'ListDisplayVideo360AdvertiserLinkProposalsRequest', +'ListDisplayVideo360AdvertiserLinkProposalsResponse', +'ListDisplayVideo360AdvertiserLinksRequest', +'ListDisplayVideo360AdvertiserLinksResponse', +'ListEventCreateRulesRequest', +'ListEventCreateRulesResponse', +'ListEventEditRulesRequest', +'ListEventEditRulesResponse', +'ListExpandedDataSetsRequest', +'ListExpandedDataSetsResponse', +'ListFirebaseLinksRequest', +'ListFirebaseLinksResponse', +'ListGoogleAdsLinksRequest', +'ListGoogleAdsLinksResponse', +'ListKeyEventsRequest', +'ListKeyEventsResponse', +'ListMeasurementProtocolSecretsRequest', +'ListMeasurementProtocolSecretsResponse', +'ListPropertiesRequest', +'ListPropertiesResponse', +'ListRollupPropertySourceLinksRequest', +'ListRollupPropertySourceLinksResponse', +'ListSKAdNetworkConversionValueSchemasRequest', +'ListSKAdNetworkConversionValueSchemasResponse', +'ListSearchAds360LinksRequest', +'ListSearchAds360LinksResponse', +'ListSubpropertyEventFiltersRequest', +'ListSubpropertyEventFiltersResponse', +'MatchingCondition', +'MeasurementProtocolSecret', +'NumericValue', +'ParameterMutation', +'PostbackWindow', +'Property', +'PropertySummary', +'PropertyType', +'ProvisionAccountTicketRequest', +'ProvisionAccountTicketResponse', +'ProvisionSubpropertyRequest', +'ProvisionSubpropertyResponse', +'ReorderEventEditRulesRequest', +'RollupPropertySourceLink', +'RunAccessReportRequest', +'RunAccessReportResponse', +'SKAdNetworkConversionValueSchema', +'SearchAds360Link', +'SearchChangeHistoryEventsRequest', +'SearchChangeHistoryEventsResponse', +'ServiceLevel', +'SetAutomatedGa4ConfigurationOptOutRequest', +'SetAutomatedGa4ConfigurationOptOutResponse', +'SubpropertyEventFilter', +'SubpropertyEventFilterClause', +'SubpropertyEventFilterCondition', +'SubpropertyEventFilterExpression', +'SubpropertyEventFilterExpressionList', +'UpdateAccessBindingRequest', +'UpdateAccountRequest', +'UpdateAttributionSettingsRequest', +'UpdateAudienceRequest', +'UpdateBigQueryLinkRequest', +'UpdateCalculatedMetricRequest', +'UpdateChannelGroupRequest', +'UpdateConversionEventRequest', +'UpdateCustomDimensionRequest', +'UpdateCustomMetricRequest', +'UpdateDataRedactionSettingsRequest', +'UpdateDataRetentionSettingsRequest', +'UpdateDataStreamRequest', +'UpdateDisplayVideo360AdvertiserLinkRequest', +'UpdateEnhancedMeasurementSettingsRequest', +'UpdateEventCreateRuleRequest', +'UpdateEventEditRuleRequest', +'UpdateExpandedDataSetRequest', +'UpdateGoogleAdsLinkRequest', +'UpdateGoogleSignalsSettingsRequest', +'UpdateKeyEventRequest', +'UpdateMeasurementProtocolSecretRequest', +'UpdatePropertyRequest', +'UpdateSKAdNetworkConversionValueSchemaRequest', +'UpdateSearchAds360LinkRequest', +'UpdateSubpropertyEventFilterRequest', +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/gapic_metadata.json b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/gapic_metadata.json new file mode 100644 index 000000000000..d379bf7a5952 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/gapic_metadata.json @@ -0,0 +1,2278 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.analytics.admin_v1alpha", + "protoPackage": "google.analytics.admin.v1alpha", + "schema": "1.0", + "services": { + "AnalyticsAdminService": { + "clients": { + "grpc": { + "libraryClient": "AnalyticsAdminServiceClient", + "rpcs": { + "AcknowledgeUserDataCollection": { + "methods": [ + "acknowledge_user_data_collection" + ] + }, + "ApproveDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "approve_display_video360_advertiser_link_proposal" + ] + }, + "ArchiveAudience": { + "methods": [ + "archive_audience" + ] + }, + "ArchiveCustomDimension": { + "methods": [ + "archive_custom_dimension" + ] + }, + "ArchiveCustomMetric": { + "methods": [ + "archive_custom_metric" + ] + }, + "BatchCreateAccessBindings": { + "methods": [ + "batch_create_access_bindings" + ] + }, + "BatchDeleteAccessBindings": { + "methods": [ + "batch_delete_access_bindings" + ] + }, + "BatchGetAccessBindings": { + "methods": [ + "batch_get_access_bindings" + ] + }, + "BatchUpdateAccessBindings": { + "methods": [ + "batch_update_access_bindings" + ] + }, + "CancelDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "cancel_display_video360_advertiser_link_proposal" + ] + }, + "CreateAccessBinding": { + "methods": [ + "create_access_binding" + ] + }, + "CreateAdSenseLink": { + "methods": [ + "create_ad_sense_link" + ] + }, + "CreateAudience": { + "methods": [ + "create_audience" + ] + }, + "CreateBigQueryLink": { + "methods": [ + "create_big_query_link" + ] + }, + "CreateCalculatedMetric": { + "methods": [ + "create_calculated_metric" + ] + }, + "CreateChannelGroup": { + "methods": [ + "create_channel_group" + ] + }, + "CreateConnectedSiteTag": { + "methods": [ + "create_connected_site_tag" + ] + }, + "CreateConversionEvent": { + "methods": [ + "create_conversion_event" + ] + }, + "CreateCustomDimension": { + "methods": [ + "create_custom_dimension" + ] + }, + "CreateCustomMetric": { + "methods": [ + "create_custom_metric" + ] + }, + "CreateDataStream": { + "methods": [ + "create_data_stream" + ] + }, + "CreateDisplayVideo360AdvertiserLink": { + "methods": [ + "create_display_video360_advertiser_link" + ] + }, + "CreateDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "create_display_video360_advertiser_link_proposal" + ] + }, + "CreateEventCreateRule": { + "methods": [ + "create_event_create_rule" + ] + }, + "CreateEventEditRule": { + "methods": [ + "create_event_edit_rule" + ] + }, + "CreateExpandedDataSet": { + "methods": [ + "create_expanded_data_set" + ] + }, + "CreateFirebaseLink": { + "methods": [ + "create_firebase_link" + ] + }, + "CreateGoogleAdsLink": { + "methods": [ + "create_google_ads_link" + ] + }, + "CreateKeyEvent": { + "methods": [ + "create_key_event" + ] + }, + "CreateMeasurementProtocolSecret": { + "methods": [ + "create_measurement_protocol_secret" + ] + }, + "CreateProperty": { + "methods": [ + "create_property" + ] + }, + "CreateRollupProperty": { + "methods": [ + "create_rollup_property" + ] + }, + "CreateRollupPropertySourceLink": { + "methods": [ + "create_rollup_property_source_link" + ] + }, + "CreateSKAdNetworkConversionValueSchema": { + "methods": [ + "create_sk_ad_network_conversion_value_schema" + ] + }, + "CreateSearchAds360Link": { + "methods": [ + "create_search_ads360_link" + ] + }, + "CreateSubpropertyEventFilter": { + "methods": [ + "create_subproperty_event_filter" + ] + }, + "DeleteAccessBinding": { + "methods": [ + "delete_access_binding" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "DeleteAdSenseLink": { + "methods": [ + "delete_ad_sense_link" + ] + }, + "DeleteBigQueryLink": { + "methods": [ + "delete_big_query_link" + ] + }, + "DeleteCalculatedMetric": { + "methods": [ + "delete_calculated_metric" + ] + }, + "DeleteChannelGroup": { + "methods": [ + "delete_channel_group" + ] + }, + "DeleteConnectedSiteTag": { + "methods": [ + "delete_connected_site_tag" + ] + }, + "DeleteConversionEvent": { + "methods": [ + "delete_conversion_event" + ] + }, + "DeleteDataStream": { + "methods": [ + "delete_data_stream" + ] + }, + "DeleteDisplayVideo360AdvertiserLink": { + "methods": [ + "delete_display_video360_advertiser_link" + ] + }, + "DeleteDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "delete_display_video360_advertiser_link_proposal" + ] + }, + "DeleteEventCreateRule": { + "methods": [ + "delete_event_create_rule" + ] + }, + "DeleteEventEditRule": { + "methods": [ + "delete_event_edit_rule" + ] + }, + "DeleteExpandedDataSet": { + "methods": [ + "delete_expanded_data_set" + ] + }, + "DeleteFirebaseLink": { + "methods": [ + "delete_firebase_link" + ] + }, + "DeleteGoogleAdsLink": { + "methods": [ + "delete_google_ads_link" + ] + }, + "DeleteKeyEvent": { + "methods": [ + "delete_key_event" + ] + }, + "DeleteMeasurementProtocolSecret": { + "methods": [ + "delete_measurement_protocol_secret" + ] + }, + "DeleteProperty": { + "methods": [ + "delete_property" + ] + }, + "DeleteRollupPropertySourceLink": { + "methods": [ + "delete_rollup_property_source_link" + ] + }, + "DeleteSKAdNetworkConversionValueSchema": { + "methods": [ + "delete_sk_ad_network_conversion_value_schema" + ] + }, + "DeleteSearchAds360Link": { + "methods": [ + "delete_search_ads360_link" + ] + }, + "DeleteSubpropertyEventFilter": { + "methods": [ + "delete_subproperty_event_filter" + ] + }, + "FetchAutomatedGa4ConfigurationOptOut": { + "methods": [ + "fetch_automated_ga4_configuration_opt_out" + ] + }, + "FetchConnectedGa4Property": { + "methods": [ + "fetch_connected_ga4_property" + ] + }, + "GetAccessBinding": { + "methods": [ + "get_access_binding" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "GetAdSenseLink": { + "methods": [ + "get_ad_sense_link" + ] + }, + "GetAttributionSettings": { + "methods": [ + "get_attribution_settings" + ] + }, + "GetAudience": { + "methods": [ + "get_audience" + ] + }, + "GetBigQueryLink": { + "methods": [ + "get_big_query_link" + ] + }, + "GetCalculatedMetric": { + "methods": [ + "get_calculated_metric" + ] + }, + "GetChannelGroup": { + "methods": [ + "get_channel_group" + ] + }, + "GetConversionEvent": { + "methods": [ + "get_conversion_event" + ] + }, + "GetCustomDimension": { + "methods": [ + "get_custom_dimension" + ] + }, + "GetCustomMetric": { + "methods": [ + "get_custom_metric" + ] + }, + "GetDataRedactionSettings": { + "methods": [ + "get_data_redaction_settings" + ] + }, + "GetDataRetentionSettings": { + "methods": [ + "get_data_retention_settings" + ] + }, + "GetDataSharingSettings": { + "methods": [ + "get_data_sharing_settings" + ] + }, + "GetDataStream": { + "methods": [ + "get_data_stream" + ] + }, + "GetDisplayVideo360AdvertiserLink": { + "methods": [ + "get_display_video360_advertiser_link" + ] + }, + "GetDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "get_display_video360_advertiser_link_proposal" + ] + }, + "GetEnhancedMeasurementSettings": { + "methods": [ + "get_enhanced_measurement_settings" + ] + }, + "GetEventCreateRule": { + "methods": [ + "get_event_create_rule" + ] + }, + "GetEventEditRule": { + "methods": [ + "get_event_edit_rule" + ] + }, + "GetExpandedDataSet": { + "methods": [ + "get_expanded_data_set" + ] + }, + "GetGlobalSiteTag": { + "methods": [ + "get_global_site_tag" + ] + }, + "GetGoogleSignalsSettings": { + "methods": [ + "get_google_signals_settings" + ] + }, + "GetKeyEvent": { + "methods": [ + "get_key_event" + ] + }, + "GetMeasurementProtocolSecret": { + "methods": [ + "get_measurement_protocol_secret" + ] + }, + "GetProperty": { + "methods": [ + "get_property" + ] + }, + "GetRollupPropertySourceLink": { + "methods": [ + "get_rollup_property_source_link" + ] + }, + "GetSKAdNetworkConversionValueSchema": { + "methods": [ + "get_sk_ad_network_conversion_value_schema" + ] + }, + "GetSearchAds360Link": { + "methods": [ + "get_search_ads360_link" + ] + }, + "GetSubpropertyEventFilter": { + "methods": [ + "get_subproperty_event_filter" + ] + }, + "ListAccessBindings": { + "methods": [ + "list_access_bindings" + ] + }, + "ListAccountSummaries": { + "methods": [ + "list_account_summaries" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListAdSenseLinks": { + "methods": [ + "list_ad_sense_links" + ] + }, + "ListAudiences": { + "methods": [ + "list_audiences" + ] + }, + "ListBigQueryLinks": { + "methods": [ + "list_big_query_links" + ] + }, + "ListCalculatedMetrics": { + "methods": [ + "list_calculated_metrics" + ] + }, + "ListChannelGroups": { + "methods": [ + "list_channel_groups" + ] + }, + "ListConnectedSiteTags": { + "methods": [ + "list_connected_site_tags" + ] + }, + "ListConversionEvents": { + "methods": [ + "list_conversion_events" + ] + }, + "ListCustomDimensions": { + "methods": [ + "list_custom_dimensions" + ] + }, + "ListCustomMetrics": { + "methods": [ + "list_custom_metrics" + ] + }, + "ListDataStreams": { + "methods": [ + "list_data_streams" + ] + }, + "ListDisplayVideo360AdvertiserLinkProposals": { + "methods": [ + "list_display_video360_advertiser_link_proposals" + ] + }, + "ListDisplayVideo360AdvertiserLinks": { + "methods": [ + "list_display_video360_advertiser_links" + ] + }, + "ListEventCreateRules": { + "methods": [ + "list_event_create_rules" + ] + }, + "ListEventEditRules": { + "methods": [ + "list_event_edit_rules" + ] + }, + "ListExpandedDataSets": { + "methods": [ + "list_expanded_data_sets" + ] + }, + "ListFirebaseLinks": { + "methods": [ + "list_firebase_links" + ] + }, + "ListGoogleAdsLinks": { + "methods": [ + "list_google_ads_links" + ] + }, + "ListKeyEvents": { + "methods": [ + "list_key_events" + ] + }, + "ListMeasurementProtocolSecrets": { + "methods": [ + "list_measurement_protocol_secrets" + ] + }, + "ListProperties": { + "methods": [ + "list_properties" + ] + }, + "ListRollupPropertySourceLinks": { + "methods": [ + "list_rollup_property_source_links" + ] + }, + "ListSKAdNetworkConversionValueSchemas": { + "methods": [ + "list_sk_ad_network_conversion_value_schemas" + ] + }, + "ListSearchAds360Links": { + "methods": [ + "list_search_ads360_links" + ] + }, + "ListSubpropertyEventFilters": { + "methods": [ + "list_subproperty_event_filters" + ] + }, + "ProvisionAccountTicket": { + "methods": [ + "provision_account_ticket" + ] + }, + "ProvisionSubproperty": { + "methods": [ + "provision_subproperty" + ] + }, + "ReorderEventEditRules": { + "methods": [ + "reorder_event_edit_rules" + ] + }, + "RunAccessReport": { + "methods": [ + "run_access_report" + ] + }, + "SearchChangeHistoryEvents": { + "methods": [ + "search_change_history_events" + ] + }, + "SetAutomatedGa4ConfigurationOptOut": { + "methods": [ + "set_automated_ga4_configuration_opt_out" + ] + }, + "UpdateAccessBinding": { + "methods": [ + "update_access_binding" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + }, + "UpdateAttributionSettings": { + "methods": [ + "update_attribution_settings" + ] + }, + "UpdateAudience": { + "methods": [ + "update_audience" + ] + }, + "UpdateBigQueryLink": { + "methods": [ + "update_big_query_link" + ] + }, + "UpdateCalculatedMetric": { + "methods": [ + "update_calculated_metric" + ] + }, + "UpdateChannelGroup": { + "methods": [ + "update_channel_group" + ] + }, + "UpdateConversionEvent": { + "methods": [ + "update_conversion_event" + ] + }, + "UpdateCustomDimension": { + "methods": [ + "update_custom_dimension" + ] + }, + "UpdateCustomMetric": { + "methods": [ + "update_custom_metric" + ] + }, + "UpdateDataRedactionSettings": { + "methods": [ + "update_data_redaction_settings" + ] + }, + "UpdateDataRetentionSettings": { + "methods": [ + "update_data_retention_settings" + ] + }, + "UpdateDataStream": { + "methods": [ + "update_data_stream" + ] + }, + "UpdateDisplayVideo360AdvertiserLink": { + "methods": [ + "update_display_video360_advertiser_link" + ] + }, + "UpdateEnhancedMeasurementSettings": { + "methods": [ + "update_enhanced_measurement_settings" + ] + }, + "UpdateEventCreateRule": { + "methods": [ + "update_event_create_rule" + ] + }, + "UpdateEventEditRule": { + "methods": [ + "update_event_edit_rule" + ] + }, + "UpdateExpandedDataSet": { + "methods": [ + "update_expanded_data_set" + ] + }, + "UpdateGoogleAdsLink": { + "methods": [ + "update_google_ads_link" + ] + }, + "UpdateGoogleSignalsSettings": { + "methods": [ + "update_google_signals_settings" + ] + }, + "UpdateKeyEvent": { + "methods": [ + "update_key_event" + ] + }, + "UpdateMeasurementProtocolSecret": { + "methods": [ + "update_measurement_protocol_secret" + ] + }, + "UpdateProperty": { + "methods": [ + "update_property" + ] + }, + "UpdateSKAdNetworkConversionValueSchema": { + "methods": [ + "update_sk_ad_network_conversion_value_schema" + ] + }, + "UpdateSearchAds360Link": { + "methods": [ + "update_search_ads360_link" + ] + }, + "UpdateSubpropertyEventFilter": { + "methods": [ + "update_subproperty_event_filter" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AnalyticsAdminServiceAsyncClient", + "rpcs": { + "AcknowledgeUserDataCollection": { + "methods": [ + "acknowledge_user_data_collection" + ] + }, + "ApproveDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "approve_display_video360_advertiser_link_proposal" + ] + }, + "ArchiveAudience": { + "methods": [ + "archive_audience" + ] + }, + "ArchiveCustomDimension": { + "methods": [ + "archive_custom_dimension" + ] + }, + "ArchiveCustomMetric": { + "methods": [ + "archive_custom_metric" + ] + }, + "BatchCreateAccessBindings": { + "methods": [ + "batch_create_access_bindings" + ] + }, + "BatchDeleteAccessBindings": { + "methods": [ + "batch_delete_access_bindings" + ] + }, + "BatchGetAccessBindings": { + "methods": [ + "batch_get_access_bindings" + ] + }, + "BatchUpdateAccessBindings": { + "methods": [ + "batch_update_access_bindings" + ] + }, + "CancelDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "cancel_display_video360_advertiser_link_proposal" + ] + }, + "CreateAccessBinding": { + "methods": [ + "create_access_binding" + ] + }, + "CreateAdSenseLink": { + "methods": [ + "create_ad_sense_link" + ] + }, + "CreateAudience": { + "methods": [ + "create_audience" + ] + }, + "CreateBigQueryLink": { + "methods": [ + "create_big_query_link" + ] + }, + "CreateCalculatedMetric": { + "methods": [ + "create_calculated_metric" + ] + }, + "CreateChannelGroup": { + "methods": [ + "create_channel_group" + ] + }, + "CreateConnectedSiteTag": { + "methods": [ + "create_connected_site_tag" + ] + }, + "CreateConversionEvent": { + "methods": [ + "create_conversion_event" + ] + }, + "CreateCustomDimension": { + "methods": [ + "create_custom_dimension" + ] + }, + "CreateCustomMetric": { + "methods": [ + "create_custom_metric" + ] + }, + "CreateDataStream": { + "methods": [ + "create_data_stream" + ] + }, + "CreateDisplayVideo360AdvertiserLink": { + "methods": [ + "create_display_video360_advertiser_link" + ] + }, + "CreateDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "create_display_video360_advertiser_link_proposal" + ] + }, + "CreateEventCreateRule": { + "methods": [ + "create_event_create_rule" + ] + }, + "CreateEventEditRule": { + "methods": [ + "create_event_edit_rule" + ] + }, + "CreateExpandedDataSet": { + "methods": [ + "create_expanded_data_set" + ] + }, + "CreateFirebaseLink": { + "methods": [ + "create_firebase_link" + ] + }, + "CreateGoogleAdsLink": { + "methods": [ + "create_google_ads_link" + ] + }, + "CreateKeyEvent": { + "methods": [ + "create_key_event" + ] + }, + "CreateMeasurementProtocolSecret": { + "methods": [ + "create_measurement_protocol_secret" + ] + }, + "CreateProperty": { + "methods": [ + "create_property" + ] + }, + "CreateRollupProperty": { + "methods": [ + "create_rollup_property" + ] + }, + "CreateRollupPropertySourceLink": { + "methods": [ + "create_rollup_property_source_link" + ] + }, + "CreateSKAdNetworkConversionValueSchema": { + "methods": [ + "create_sk_ad_network_conversion_value_schema" + ] + }, + "CreateSearchAds360Link": { + "methods": [ + "create_search_ads360_link" + ] + }, + "CreateSubpropertyEventFilter": { + "methods": [ + "create_subproperty_event_filter" + ] + }, + "DeleteAccessBinding": { + "methods": [ + "delete_access_binding" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "DeleteAdSenseLink": { + "methods": [ + "delete_ad_sense_link" + ] + }, + "DeleteBigQueryLink": { + "methods": [ + "delete_big_query_link" + ] + }, + "DeleteCalculatedMetric": { + "methods": [ + "delete_calculated_metric" + ] + }, + "DeleteChannelGroup": { + "methods": [ + "delete_channel_group" + ] + }, + "DeleteConnectedSiteTag": { + "methods": [ + "delete_connected_site_tag" + ] + }, + "DeleteConversionEvent": { + "methods": [ + "delete_conversion_event" + ] + }, + "DeleteDataStream": { + "methods": [ + "delete_data_stream" + ] + }, + "DeleteDisplayVideo360AdvertiserLink": { + "methods": [ + "delete_display_video360_advertiser_link" + ] + }, + "DeleteDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "delete_display_video360_advertiser_link_proposal" + ] + }, + "DeleteEventCreateRule": { + "methods": [ + "delete_event_create_rule" + ] + }, + "DeleteEventEditRule": { + "methods": [ + "delete_event_edit_rule" + ] + }, + "DeleteExpandedDataSet": { + "methods": [ + "delete_expanded_data_set" + ] + }, + "DeleteFirebaseLink": { + "methods": [ + "delete_firebase_link" + ] + }, + "DeleteGoogleAdsLink": { + "methods": [ + "delete_google_ads_link" + ] + }, + "DeleteKeyEvent": { + "methods": [ + "delete_key_event" + ] + }, + "DeleteMeasurementProtocolSecret": { + "methods": [ + "delete_measurement_protocol_secret" + ] + }, + "DeleteProperty": { + "methods": [ + "delete_property" + ] + }, + "DeleteRollupPropertySourceLink": { + "methods": [ + "delete_rollup_property_source_link" + ] + }, + "DeleteSKAdNetworkConversionValueSchema": { + "methods": [ + "delete_sk_ad_network_conversion_value_schema" + ] + }, + "DeleteSearchAds360Link": { + "methods": [ + "delete_search_ads360_link" + ] + }, + "DeleteSubpropertyEventFilter": { + "methods": [ + "delete_subproperty_event_filter" + ] + }, + "FetchAutomatedGa4ConfigurationOptOut": { + "methods": [ + "fetch_automated_ga4_configuration_opt_out" + ] + }, + "FetchConnectedGa4Property": { + "methods": [ + "fetch_connected_ga4_property" + ] + }, + "GetAccessBinding": { + "methods": [ + "get_access_binding" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "GetAdSenseLink": { + "methods": [ + "get_ad_sense_link" + ] + }, + "GetAttributionSettings": { + "methods": [ + "get_attribution_settings" + ] + }, + "GetAudience": { + "methods": [ + "get_audience" + ] + }, + "GetBigQueryLink": { + "methods": [ + "get_big_query_link" + ] + }, + "GetCalculatedMetric": { + "methods": [ + "get_calculated_metric" + ] + }, + "GetChannelGroup": { + "methods": [ + "get_channel_group" + ] + }, + "GetConversionEvent": { + "methods": [ + "get_conversion_event" + ] + }, + "GetCustomDimension": { + "methods": [ + "get_custom_dimension" + ] + }, + "GetCustomMetric": { + "methods": [ + "get_custom_metric" + ] + }, + "GetDataRedactionSettings": { + "methods": [ + "get_data_redaction_settings" + ] + }, + "GetDataRetentionSettings": { + "methods": [ + "get_data_retention_settings" + ] + }, + "GetDataSharingSettings": { + "methods": [ + "get_data_sharing_settings" + ] + }, + "GetDataStream": { + "methods": [ + "get_data_stream" + ] + }, + "GetDisplayVideo360AdvertiserLink": { + "methods": [ + "get_display_video360_advertiser_link" + ] + }, + "GetDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "get_display_video360_advertiser_link_proposal" + ] + }, + "GetEnhancedMeasurementSettings": { + "methods": [ + "get_enhanced_measurement_settings" + ] + }, + "GetEventCreateRule": { + "methods": [ + "get_event_create_rule" + ] + }, + "GetEventEditRule": { + "methods": [ + "get_event_edit_rule" + ] + }, + "GetExpandedDataSet": { + "methods": [ + "get_expanded_data_set" + ] + }, + "GetGlobalSiteTag": { + "methods": [ + "get_global_site_tag" + ] + }, + "GetGoogleSignalsSettings": { + "methods": [ + "get_google_signals_settings" + ] + }, + "GetKeyEvent": { + "methods": [ + "get_key_event" + ] + }, + "GetMeasurementProtocolSecret": { + "methods": [ + "get_measurement_protocol_secret" + ] + }, + "GetProperty": { + "methods": [ + "get_property" + ] + }, + "GetRollupPropertySourceLink": { + "methods": [ + "get_rollup_property_source_link" + ] + }, + "GetSKAdNetworkConversionValueSchema": { + "methods": [ + "get_sk_ad_network_conversion_value_schema" + ] + }, + "GetSearchAds360Link": { + "methods": [ + "get_search_ads360_link" + ] + }, + "GetSubpropertyEventFilter": { + "methods": [ + "get_subproperty_event_filter" + ] + }, + "ListAccessBindings": { + "methods": [ + "list_access_bindings" + ] + }, + "ListAccountSummaries": { + "methods": [ + "list_account_summaries" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListAdSenseLinks": { + "methods": [ + "list_ad_sense_links" + ] + }, + "ListAudiences": { + "methods": [ + "list_audiences" + ] + }, + "ListBigQueryLinks": { + "methods": [ + "list_big_query_links" + ] + }, + "ListCalculatedMetrics": { + "methods": [ + "list_calculated_metrics" + ] + }, + "ListChannelGroups": { + "methods": [ + "list_channel_groups" + ] + }, + "ListConnectedSiteTags": { + "methods": [ + "list_connected_site_tags" + ] + }, + "ListConversionEvents": { + "methods": [ + "list_conversion_events" + ] + }, + "ListCustomDimensions": { + "methods": [ + "list_custom_dimensions" + ] + }, + "ListCustomMetrics": { + "methods": [ + "list_custom_metrics" + ] + }, + "ListDataStreams": { + "methods": [ + "list_data_streams" + ] + }, + "ListDisplayVideo360AdvertiserLinkProposals": { + "methods": [ + "list_display_video360_advertiser_link_proposals" + ] + }, + "ListDisplayVideo360AdvertiserLinks": { + "methods": [ + "list_display_video360_advertiser_links" + ] + }, + "ListEventCreateRules": { + "methods": [ + "list_event_create_rules" + ] + }, + "ListEventEditRules": { + "methods": [ + "list_event_edit_rules" + ] + }, + "ListExpandedDataSets": { + "methods": [ + "list_expanded_data_sets" + ] + }, + "ListFirebaseLinks": { + "methods": [ + "list_firebase_links" + ] + }, + "ListGoogleAdsLinks": { + "methods": [ + "list_google_ads_links" + ] + }, + "ListKeyEvents": { + "methods": [ + "list_key_events" + ] + }, + "ListMeasurementProtocolSecrets": { + "methods": [ + "list_measurement_protocol_secrets" + ] + }, + "ListProperties": { + "methods": [ + "list_properties" + ] + }, + "ListRollupPropertySourceLinks": { + "methods": [ + "list_rollup_property_source_links" + ] + }, + "ListSKAdNetworkConversionValueSchemas": { + "methods": [ + "list_sk_ad_network_conversion_value_schemas" + ] + }, + "ListSearchAds360Links": { + "methods": [ + "list_search_ads360_links" + ] + }, + "ListSubpropertyEventFilters": { + "methods": [ + "list_subproperty_event_filters" + ] + }, + "ProvisionAccountTicket": { + "methods": [ + "provision_account_ticket" + ] + }, + "ProvisionSubproperty": { + "methods": [ + "provision_subproperty" + ] + }, + "ReorderEventEditRules": { + "methods": [ + "reorder_event_edit_rules" + ] + }, + "RunAccessReport": { + "methods": [ + "run_access_report" + ] + }, + "SearchChangeHistoryEvents": { + "methods": [ + "search_change_history_events" + ] + }, + "SetAutomatedGa4ConfigurationOptOut": { + "methods": [ + "set_automated_ga4_configuration_opt_out" + ] + }, + "UpdateAccessBinding": { + "methods": [ + "update_access_binding" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + }, + "UpdateAttributionSettings": { + "methods": [ + "update_attribution_settings" + ] + }, + "UpdateAudience": { + "methods": [ + "update_audience" + ] + }, + "UpdateBigQueryLink": { + "methods": [ + "update_big_query_link" + ] + }, + "UpdateCalculatedMetric": { + "methods": [ + "update_calculated_metric" + ] + }, + "UpdateChannelGroup": { + "methods": [ + "update_channel_group" + ] + }, + "UpdateConversionEvent": { + "methods": [ + "update_conversion_event" + ] + }, + "UpdateCustomDimension": { + "methods": [ + "update_custom_dimension" + ] + }, + "UpdateCustomMetric": { + "methods": [ + "update_custom_metric" + ] + }, + "UpdateDataRedactionSettings": { + "methods": [ + "update_data_redaction_settings" + ] + }, + "UpdateDataRetentionSettings": { + "methods": [ + "update_data_retention_settings" + ] + }, + "UpdateDataStream": { + "methods": [ + "update_data_stream" + ] + }, + "UpdateDisplayVideo360AdvertiserLink": { + "methods": [ + "update_display_video360_advertiser_link" + ] + }, + "UpdateEnhancedMeasurementSettings": { + "methods": [ + "update_enhanced_measurement_settings" + ] + }, + "UpdateEventCreateRule": { + "methods": [ + "update_event_create_rule" + ] + }, + "UpdateEventEditRule": { + "methods": [ + "update_event_edit_rule" + ] + }, + "UpdateExpandedDataSet": { + "methods": [ + "update_expanded_data_set" + ] + }, + "UpdateGoogleAdsLink": { + "methods": [ + "update_google_ads_link" + ] + }, + "UpdateGoogleSignalsSettings": { + "methods": [ + "update_google_signals_settings" + ] + }, + "UpdateKeyEvent": { + "methods": [ + "update_key_event" + ] + }, + "UpdateMeasurementProtocolSecret": { + "methods": [ + "update_measurement_protocol_secret" + ] + }, + "UpdateProperty": { + "methods": [ + "update_property" + ] + }, + "UpdateSKAdNetworkConversionValueSchema": { + "methods": [ + "update_sk_ad_network_conversion_value_schema" + ] + }, + "UpdateSearchAds360Link": { + "methods": [ + "update_search_ads360_link" + ] + }, + "UpdateSubpropertyEventFilter": { + "methods": [ + "update_subproperty_event_filter" + ] + } + } + }, + "rest": { + "libraryClient": "AnalyticsAdminServiceClient", + "rpcs": { + "AcknowledgeUserDataCollection": { + "methods": [ + "acknowledge_user_data_collection" + ] + }, + "ApproveDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "approve_display_video360_advertiser_link_proposal" + ] + }, + "ArchiveAudience": { + "methods": [ + "archive_audience" + ] + }, + "ArchiveCustomDimension": { + "methods": [ + "archive_custom_dimension" + ] + }, + "ArchiveCustomMetric": { + "methods": [ + "archive_custom_metric" + ] + }, + "BatchCreateAccessBindings": { + "methods": [ + "batch_create_access_bindings" + ] + }, + "BatchDeleteAccessBindings": { + "methods": [ + "batch_delete_access_bindings" + ] + }, + "BatchGetAccessBindings": { + "methods": [ + "batch_get_access_bindings" + ] + }, + "BatchUpdateAccessBindings": { + "methods": [ + "batch_update_access_bindings" + ] + }, + "CancelDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "cancel_display_video360_advertiser_link_proposal" + ] + }, + "CreateAccessBinding": { + "methods": [ + "create_access_binding" + ] + }, + "CreateAdSenseLink": { + "methods": [ + "create_ad_sense_link" + ] + }, + "CreateAudience": { + "methods": [ + "create_audience" + ] + }, + "CreateBigQueryLink": { + "methods": [ + "create_big_query_link" + ] + }, + "CreateCalculatedMetric": { + "methods": [ + "create_calculated_metric" + ] + }, + "CreateChannelGroup": { + "methods": [ + "create_channel_group" + ] + }, + "CreateConnectedSiteTag": { + "methods": [ + "create_connected_site_tag" + ] + }, + "CreateConversionEvent": { + "methods": [ + "create_conversion_event" + ] + }, + "CreateCustomDimension": { + "methods": [ + "create_custom_dimension" + ] + }, + "CreateCustomMetric": { + "methods": [ + "create_custom_metric" + ] + }, + "CreateDataStream": { + "methods": [ + "create_data_stream" + ] + }, + "CreateDisplayVideo360AdvertiserLink": { + "methods": [ + "create_display_video360_advertiser_link" + ] + }, + "CreateDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "create_display_video360_advertiser_link_proposal" + ] + }, + "CreateEventCreateRule": { + "methods": [ + "create_event_create_rule" + ] + }, + "CreateEventEditRule": { + "methods": [ + "create_event_edit_rule" + ] + }, + "CreateExpandedDataSet": { + "methods": [ + "create_expanded_data_set" + ] + }, + "CreateFirebaseLink": { + "methods": [ + "create_firebase_link" + ] + }, + "CreateGoogleAdsLink": { + "methods": [ + "create_google_ads_link" + ] + }, + "CreateKeyEvent": { + "methods": [ + "create_key_event" + ] + }, + "CreateMeasurementProtocolSecret": { + "methods": [ + "create_measurement_protocol_secret" + ] + }, + "CreateProperty": { + "methods": [ + "create_property" + ] + }, + "CreateRollupProperty": { + "methods": [ + "create_rollup_property" + ] + }, + "CreateRollupPropertySourceLink": { + "methods": [ + "create_rollup_property_source_link" + ] + }, + "CreateSKAdNetworkConversionValueSchema": { + "methods": [ + "create_sk_ad_network_conversion_value_schema" + ] + }, + "CreateSearchAds360Link": { + "methods": [ + "create_search_ads360_link" + ] + }, + "CreateSubpropertyEventFilter": { + "methods": [ + "create_subproperty_event_filter" + ] + }, + "DeleteAccessBinding": { + "methods": [ + "delete_access_binding" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "DeleteAdSenseLink": { + "methods": [ + "delete_ad_sense_link" + ] + }, + "DeleteBigQueryLink": { + "methods": [ + "delete_big_query_link" + ] + }, + "DeleteCalculatedMetric": { + "methods": [ + "delete_calculated_metric" + ] + }, + "DeleteChannelGroup": { + "methods": [ + "delete_channel_group" + ] + }, + "DeleteConnectedSiteTag": { + "methods": [ + "delete_connected_site_tag" + ] + }, + "DeleteConversionEvent": { + "methods": [ + "delete_conversion_event" + ] + }, + "DeleteDataStream": { + "methods": [ + "delete_data_stream" + ] + }, + "DeleteDisplayVideo360AdvertiserLink": { + "methods": [ + "delete_display_video360_advertiser_link" + ] + }, + "DeleteDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "delete_display_video360_advertiser_link_proposal" + ] + }, + "DeleteEventCreateRule": { + "methods": [ + "delete_event_create_rule" + ] + }, + "DeleteEventEditRule": { + "methods": [ + "delete_event_edit_rule" + ] + }, + "DeleteExpandedDataSet": { + "methods": [ + "delete_expanded_data_set" + ] + }, + "DeleteFirebaseLink": { + "methods": [ + "delete_firebase_link" + ] + }, + "DeleteGoogleAdsLink": { + "methods": [ + "delete_google_ads_link" + ] + }, + "DeleteKeyEvent": { + "methods": [ + "delete_key_event" + ] + }, + "DeleteMeasurementProtocolSecret": { + "methods": [ + "delete_measurement_protocol_secret" + ] + }, + "DeleteProperty": { + "methods": [ + "delete_property" + ] + }, + "DeleteRollupPropertySourceLink": { + "methods": [ + "delete_rollup_property_source_link" + ] + }, + "DeleteSKAdNetworkConversionValueSchema": { + "methods": [ + "delete_sk_ad_network_conversion_value_schema" + ] + }, + "DeleteSearchAds360Link": { + "methods": [ + "delete_search_ads360_link" + ] + }, + "DeleteSubpropertyEventFilter": { + "methods": [ + "delete_subproperty_event_filter" + ] + }, + "FetchAutomatedGa4ConfigurationOptOut": { + "methods": [ + "fetch_automated_ga4_configuration_opt_out" + ] + }, + "FetchConnectedGa4Property": { + "methods": [ + "fetch_connected_ga4_property" + ] + }, + "GetAccessBinding": { + "methods": [ + "get_access_binding" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "GetAdSenseLink": { + "methods": [ + "get_ad_sense_link" + ] + }, + "GetAttributionSettings": { + "methods": [ + "get_attribution_settings" + ] + }, + "GetAudience": { + "methods": [ + "get_audience" + ] + }, + "GetBigQueryLink": { + "methods": [ + "get_big_query_link" + ] + }, + "GetCalculatedMetric": { + "methods": [ + "get_calculated_metric" + ] + }, + "GetChannelGroup": { + "methods": [ + "get_channel_group" + ] + }, + "GetConversionEvent": { + "methods": [ + "get_conversion_event" + ] + }, + "GetCustomDimension": { + "methods": [ + "get_custom_dimension" + ] + }, + "GetCustomMetric": { + "methods": [ + "get_custom_metric" + ] + }, + "GetDataRedactionSettings": { + "methods": [ + "get_data_redaction_settings" + ] + }, + "GetDataRetentionSettings": { + "methods": [ + "get_data_retention_settings" + ] + }, + "GetDataSharingSettings": { + "methods": [ + "get_data_sharing_settings" + ] + }, + "GetDataStream": { + "methods": [ + "get_data_stream" + ] + }, + "GetDisplayVideo360AdvertiserLink": { + "methods": [ + "get_display_video360_advertiser_link" + ] + }, + "GetDisplayVideo360AdvertiserLinkProposal": { + "methods": [ + "get_display_video360_advertiser_link_proposal" + ] + }, + "GetEnhancedMeasurementSettings": { + "methods": [ + "get_enhanced_measurement_settings" + ] + }, + "GetEventCreateRule": { + "methods": [ + "get_event_create_rule" + ] + }, + "GetEventEditRule": { + "methods": [ + "get_event_edit_rule" + ] + }, + "GetExpandedDataSet": { + "methods": [ + "get_expanded_data_set" + ] + }, + "GetGlobalSiteTag": { + "methods": [ + "get_global_site_tag" + ] + }, + "GetGoogleSignalsSettings": { + "methods": [ + "get_google_signals_settings" + ] + }, + "GetKeyEvent": { + "methods": [ + "get_key_event" + ] + }, + "GetMeasurementProtocolSecret": { + "methods": [ + "get_measurement_protocol_secret" + ] + }, + "GetProperty": { + "methods": [ + "get_property" + ] + }, + "GetRollupPropertySourceLink": { + "methods": [ + "get_rollup_property_source_link" + ] + }, + "GetSKAdNetworkConversionValueSchema": { + "methods": [ + "get_sk_ad_network_conversion_value_schema" + ] + }, + "GetSearchAds360Link": { + "methods": [ + "get_search_ads360_link" + ] + }, + "GetSubpropertyEventFilter": { + "methods": [ + "get_subproperty_event_filter" + ] + }, + "ListAccessBindings": { + "methods": [ + "list_access_bindings" + ] + }, + "ListAccountSummaries": { + "methods": [ + "list_account_summaries" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListAdSenseLinks": { + "methods": [ + "list_ad_sense_links" + ] + }, + "ListAudiences": { + "methods": [ + "list_audiences" + ] + }, + "ListBigQueryLinks": { + "methods": [ + "list_big_query_links" + ] + }, + "ListCalculatedMetrics": { + "methods": [ + "list_calculated_metrics" + ] + }, + "ListChannelGroups": { + "methods": [ + "list_channel_groups" + ] + }, + "ListConnectedSiteTags": { + "methods": [ + "list_connected_site_tags" + ] + }, + "ListConversionEvents": { + "methods": [ + "list_conversion_events" + ] + }, + "ListCustomDimensions": { + "methods": [ + "list_custom_dimensions" + ] + }, + "ListCustomMetrics": { + "methods": [ + "list_custom_metrics" + ] + }, + "ListDataStreams": { + "methods": [ + "list_data_streams" + ] + }, + "ListDisplayVideo360AdvertiserLinkProposals": { + "methods": [ + "list_display_video360_advertiser_link_proposals" + ] + }, + "ListDisplayVideo360AdvertiserLinks": { + "methods": [ + "list_display_video360_advertiser_links" + ] + }, + "ListEventCreateRules": { + "methods": [ + "list_event_create_rules" + ] + }, + "ListEventEditRules": { + "methods": [ + "list_event_edit_rules" + ] + }, + "ListExpandedDataSets": { + "methods": [ + "list_expanded_data_sets" + ] + }, + "ListFirebaseLinks": { + "methods": [ + "list_firebase_links" + ] + }, + "ListGoogleAdsLinks": { + "methods": [ + "list_google_ads_links" + ] + }, + "ListKeyEvents": { + "methods": [ + "list_key_events" + ] + }, + "ListMeasurementProtocolSecrets": { + "methods": [ + "list_measurement_protocol_secrets" + ] + }, + "ListProperties": { + "methods": [ + "list_properties" + ] + }, + "ListRollupPropertySourceLinks": { + "methods": [ + "list_rollup_property_source_links" + ] + }, + "ListSKAdNetworkConversionValueSchemas": { + "methods": [ + "list_sk_ad_network_conversion_value_schemas" + ] + }, + "ListSearchAds360Links": { + "methods": [ + "list_search_ads360_links" + ] + }, + "ListSubpropertyEventFilters": { + "methods": [ + "list_subproperty_event_filters" + ] + }, + "ProvisionAccountTicket": { + "methods": [ + "provision_account_ticket" + ] + }, + "ProvisionSubproperty": { + "methods": [ + "provision_subproperty" + ] + }, + "ReorderEventEditRules": { + "methods": [ + "reorder_event_edit_rules" + ] + }, + "RunAccessReport": { + "methods": [ + "run_access_report" + ] + }, + "SearchChangeHistoryEvents": { + "methods": [ + "search_change_history_events" + ] + }, + "SetAutomatedGa4ConfigurationOptOut": { + "methods": [ + "set_automated_ga4_configuration_opt_out" + ] + }, + "UpdateAccessBinding": { + "methods": [ + "update_access_binding" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + }, + "UpdateAttributionSettings": { + "methods": [ + "update_attribution_settings" + ] + }, + "UpdateAudience": { + "methods": [ + "update_audience" + ] + }, + "UpdateBigQueryLink": { + "methods": [ + "update_big_query_link" + ] + }, + "UpdateCalculatedMetric": { + "methods": [ + "update_calculated_metric" + ] + }, + "UpdateChannelGroup": { + "methods": [ + "update_channel_group" + ] + }, + "UpdateConversionEvent": { + "methods": [ + "update_conversion_event" + ] + }, + "UpdateCustomDimension": { + "methods": [ + "update_custom_dimension" + ] + }, + "UpdateCustomMetric": { + "methods": [ + "update_custom_metric" + ] + }, + "UpdateDataRedactionSettings": { + "methods": [ + "update_data_redaction_settings" + ] + }, + "UpdateDataRetentionSettings": { + "methods": [ + "update_data_retention_settings" + ] + }, + "UpdateDataStream": { + "methods": [ + "update_data_stream" + ] + }, + "UpdateDisplayVideo360AdvertiserLink": { + "methods": [ + "update_display_video360_advertiser_link" + ] + }, + "UpdateEnhancedMeasurementSettings": { + "methods": [ + "update_enhanced_measurement_settings" + ] + }, + "UpdateEventCreateRule": { + "methods": [ + "update_event_create_rule" + ] + }, + "UpdateEventEditRule": { + "methods": [ + "update_event_edit_rule" + ] + }, + "UpdateExpandedDataSet": { + "methods": [ + "update_expanded_data_set" + ] + }, + "UpdateGoogleAdsLink": { + "methods": [ + "update_google_ads_link" + ] + }, + "UpdateGoogleSignalsSettings": { + "methods": [ + "update_google_signals_settings" + ] + }, + "UpdateKeyEvent": { + "methods": [ + "update_key_event" + ] + }, + "UpdateMeasurementProtocolSecret": { + "methods": [ + "update_measurement_protocol_secret" + ] + }, + "UpdateProperty": { + "methods": [ + "update_property" + ] + }, + "UpdateSKAdNetworkConversionValueSchema": { + "methods": [ + "update_sk_ad_network_conversion_value_schema" + ] + }, + "UpdateSearchAds360Link": { + "methods": [ + "update_search_ads360_link" + ] + }, + "UpdateSubpropertyEventFilter": { + "methods": [ + "update_subproperty_event_filter" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/gapic_version.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/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-analytics-admin/v1alpha/google/analytics/admin_v1alpha/py.typed b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/py.typed new file mode 100644 index 000000000000..3b7eb1470672 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-analytics-admin package uses inline types. diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/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-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/__init__.py new file mode 100644 index 000000000000..64d99df43912 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_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 AnalyticsAdminServiceClient +from .async_client import AnalyticsAdminServiceAsyncClient + +__all__ = ( + 'AnalyticsAdminServiceClient', + 'AnalyticsAdminServiceAsyncClient', +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/async_client.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/async_client.py new file mode 100644 index 000000000000..6e90c952741f --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/async_client.py @@ -0,0 +1,12364 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +import warnings + +from google.analytics.admin_v1alpha 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.analytics.admin_v1alpha.services.analytics_admin_service import pagers +from google.analytics.admin_v1alpha.types import access_report +from google.analytics.admin_v1alpha.types import analytics_admin +from google.analytics.admin_v1alpha.types import audience +from google.analytics.admin_v1alpha.types import audience as gaa_audience +from google.analytics.admin_v1alpha.types import channel_group +from google.analytics.admin_v1alpha.types import channel_group as gaa_channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set +from google.analytics.admin_v1alpha.types import expanded_data_set as gaa_expanded_data_set +from google.analytics.admin_v1alpha.types import resources +from google.analytics.admin_v1alpha.types import subproperty_event_filter +from google.analytics.admin_v1alpha.types import subproperty_event_filter as gaa_subproperty_event_filter +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 .transports.base import AnalyticsAdminServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AnalyticsAdminServiceGrpcAsyncIOTransport +from .client import AnalyticsAdminServiceClient + + +class AnalyticsAdminServiceAsyncClient: + """Service Interface for the Analytics Admin API (GA4).""" + + _client: AnalyticsAdminServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AnalyticsAdminServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AnalyticsAdminServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + + access_binding_path = staticmethod(AnalyticsAdminServiceClient.access_binding_path) + parse_access_binding_path = staticmethod(AnalyticsAdminServiceClient.parse_access_binding_path) + account_path = staticmethod(AnalyticsAdminServiceClient.account_path) + parse_account_path = staticmethod(AnalyticsAdminServiceClient.parse_account_path) + account_summary_path = staticmethod(AnalyticsAdminServiceClient.account_summary_path) + parse_account_summary_path = staticmethod(AnalyticsAdminServiceClient.parse_account_summary_path) + ad_sense_link_path = staticmethod(AnalyticsAdminServiceClient.ad_sense_link_path) + parse_ad_sense_link_path = staticmethod(AnalyticsAdminServiceClient.parse_ad_sense_link_path) + attribution_settings_path = staticmethod(AnalyticsAdminServiceClient.attribution_settings_path) + parse_attribution_settings_path = staticmethod(AnalyticsAdminServiceClient.parse_attribution_settings_path) + audience_path = staticmethod(AnalyticsAdminServiceClient.audience_path) + parse_audience_path = staticmethod(AnalyticsAdminServiceClient.parse_audience_path) + big_query_link_path = staticmethod(AnalyticsAdminServiceClient.big_query_link_path) + parse_big_query_link_path = staticmethod(AnalyticsAdminServiceClient.parse_big_query_link_path) + calculated_metric_path = staticmethod(AnalyticsAdminServiceClient.calculated_metric_path) + parse_calculated_metric_path = staticmethod(AnalyticsAdminServiceClient.parse_calculated_metric_path) + channel_group_path = staticmethod(AnalyticsAdminServiceClient.channel_group_path) + parse_channel_group_path = staticmethod(AnalyticsAdminServiceClient.parse_channel_group_path) + conversion_event_path = staticmethod(AnalyticsAdminServiceClient.conversion_event_path) + parse_conversion_event_path = staticmethod(AnalyticsAdminServiceClient.parse_conversion_event_path) + custom_dimension_path = staticmethod(AnalyticsAdminServiceClient.custom_dimension_path) + parse_custom_dimension_path = staticmethod(AnalyticsAdminServiceClient.parse_custom_dimension_path) + custom_metric_path = staticmethod(AnalyticsAdminServiceClient.custom_metric_path) + parse_custom_metric_path = staticmethod(AnalyticsAdminServiceClient.parse_custom_metric_path) + data_redaction_settings_path = staticmethod(AnalyticsAdminServiceClient.data_redaction_settings_path) + parse_data_redaction_settings_path = staticmethod(AnalyticsAdminServiceClient.parse_data_redaction_settings_path) + data_retention_settings_path = staticmethod(AnalyticsAdminServiceClient.data_retention_settings_path) + parse_data_retention_settings_path = staticmethod(AnalyticsAdminServiceClient.parse_data_retention_settings_path) + data_sharing_settings_path = staticmethod(AnalyticsAdminServiceClient.data_sharing_settings_path) + parse_data_sharing_settings_path = staticmethod(AnalyticsAdminServiceClient.parse_data_sharing_settings_path) + data_stream_path = staticmethod(AnalyticsAdminServiceClient.data_stream_path) + parse_data_stream_path = staticmethod(AnalyticsAdminServiceClient.parse_data_stream_path) + display_video360_advertiser_link_path = staticmethod(AnalyticsAdminServiceClient.display_video360_advertiser_link_path) + parse_display_video360_advertiser_link_path = staticmethod(AnalyticsAdminServiceClient.parse_display_video360_advertiser_link_path) + display_video360_advertiser_link_proposal_path = staticmethod(AnalyticsAdminServiceClient.display_video360_advertiser_link_proposal_path) + parse_display_video360_advertiser_link_proposal_path = staticmethod(AnalyticsAdminServiceClient.parse_display_video360_advertiser_link_proposal_path) + enhanced_measurement_settings_path = staticmethod(AnalyticsAdminServiceClient.enhanced_measurement_settings_path) + parse_enhanced_measurement_settings_path = staticmethod(AnalyticsAdminServiceClient.parse_enhanced_measurement_settings_path) + event_create_rule_path = staticmethod(AnalyticsAdminServiceClient.event_create_rule_path) + parse_event_create_rule_path = staticmethod(AnalyticsAdminServiceClient.parse_event_create_rule_path) + event_edit_rule_path = staticmethod(AnalyticsAdminServiceClient.event_edit_rule_path) + parse_event_edit_rule_path = staticmethod(AnalyticsAdminServiceClient.parse_event_edit_rule_path) + expanded_data_set_path = staticmethod(AnalyticsAdminServiceClient.expanded_data_set_path) + parse_expanded_data_set_path = staticmethod(AnalyticsAdminServiceClient.parse_expanded_data_set_path) + firebase_link_path = staticmethod(AnalyticsAdminServiceClient.firebase_link_path) + parse_firebase_link_path = staticmethod(AnalyticsAdminServiceClient.parse_firebase_link_path) + global_site_tag_path = staticmethod(AnalyticsAdminServiceClient.global_site_tag_path) + parse_global_site_tag_path = staticmethod(AnalyticsAdminServiceClient.parse_global_site_tag_path) + google_ads_link_path = staticmethod(AnalyticsAdminServiceClient.google_ads_link_path) + parse_google_ads_link_path = staticmethod(AnalyticsAdminServiceClient.parse_google_ads_link_path) + google_signals_settings_path = staticmethod(AnalyticsAdminServiceClient.google_signals_settings_path) + parse_google_signals_settings_path = staticmethod(AnalyticsAdminServiceClient.parse_google_signals_settings_path) + key_event_path = staticmethod(AnalyticsAdminServiceClient.key_event_path) + parse_key_event_path = staticmethod(AnalyticsAdminServiceClient.parse_key_event_path) + measurement_protocol_secret_path = staticmethod(AnalyticsAdminServiceClient.measurement_protocol_secret_path) + parse_measurement_protocol_secret_path = staticmethod(AnalyticsAdminServiceClient.parse_measurement_protocol_secret_path) + organization_path = staticmethod(AnalyticsAdminServiceClient.organization_path) + parse_organization_path = staticmethod(AnalyticsAdminServiceClient.parse_organization_path) + property_path = staticmethod(AnalyticsAdminServiceClient.property_path) + parse_property_path = staticmethod(AnalyticsAdminServiceClient.parse_property_path) + rollup_property_source_link_path = staticmethod(AnalyticsAdminServiceClient.rollup_property_source_link_path) + parse_rollup_property_source_link_path = staticmethod(AnalyticsAdminServiceClient.parse_rollup_property_source_link_path) + search_ads360_link_path = staticmethod(AnalyticsAdminServiceClient.search_ads360_link_path) + parse_search_ads360_link_path = staticmethod(AnalyticsAdminServiceClient.parse_search_ads360_link_path) + sk_ad_network_conversion_value_schema_path = staticmethod(AnalyticsAdminServiceClient.sk_ad_network_conversion_value_schema_path) + parse_sk_ad_network_conversion_value_schema_path = staticmethod(AnalyticsAdminServiceClient.parse_sk_ad_network_conversion_value_schema_path) + subproperty_event_filter_path = staticmethod(AnalyticsAdminServiceClient.subproperty_event_filter_path) + parse_subproperty_event_filter_path = staticmethod(AnalyticsAdminServiceClient.parse_subproperty_event_filter_path) + common_billing_account_path = staticmethod(AnalyticsAdminServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AnalyticsAdminServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AnalyticsAdminServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AnalyticsAdminServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AnalyticsAdminServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AnalyticsAdminServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AnalyticsAdminServiceClient.common_project_path) + parse_common_project_path = staticmethod(AnalyticsAdminServiceClient.parse_common_project_path) + common_location_path = staticmethod(AnalyticsAdminServiceClient.common_location_path) + parse_common_location_path = staticmethod(AnalyticsAdminServiceClient.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: + AnalyticsAdminServiceAsyncClient: The constructed client. + """ + return AnalyticsAdminServiceClient.from_service_account_info.__func__(AnalyticsAdminServiceAsyncClient, 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: + AnalyticsAdminServiceAsyncClient: The constructed client. + """ + return AnalyticsAdminServiceClient.from_service_account_file.__func__(AnalyticsAdminServiceAsyncClient, 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 AnalyticsAdminServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AnalyticsAdminServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AnalyticsAdminServiceTransport: 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(AnalyticsAdminServiceClient).get_transport_class, type(AnalyticsAdminServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AnalyticsAdminServiceTransport, Callable[..., AnalyticsAdminServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the analytics admin service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AnalyticsAdminServiceTransport,Callable[..., AnalyticsAdminServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AnalyticsAdminServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AnalyticsAdminServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_account(self, + request: Optional[Union[analytics_admin.GetAccountRequest, 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]] = (), + ) -> resources.Account: + r"""Lookup for a single Account. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetAccountRequest, dict]]): + The request object. Request message for GetAccount RPC. + name (:class:`str`): + Required. The name of the account to + lookup. Format: accounts/{account} + Example: "accounts/100" + + 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.analytics.admin_v1alpha.types.Account: + A resource message representing a + Google Analytics account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAccountRequest): + request = analytics_admin.GetAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_accounts(self, + request: Optional[Union[analytics_admin.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAccountsAsyncPager: + r"""Returns all accounts accessible by the caller. + + Note that these accounts might not currently have GA4 + properties. Soft-deleted (ie: "trashed") accounts are + excluded by default. Returns an empty list if no + relevant accounts are found. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListAccountsRequest, dict]]): + The request object. Request message for ListAccounts RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccountsAsyncPager: + Request message for ListAccounts RPC. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccountsRequest): + request = analytics_admin.ListAccountsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_accounts] + + # 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.ListAccountsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_account(self, + request: Optional[Union[analytics_admin.DeleteAccountRequest, 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"""Marks target Account as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + accounts. However, they can be restored using the Trash + Can UI. + + If the accounts are not restored before the expiration + time, the account and all child resources (eg: + Properties, GoogleAdsLinks, Streams, AccessBindings) + will be permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteAccountRequest, dict]]): + The request object. Request message for DeleteAccount + RPC. + name (:class:`str`): + Required. The name of the Account to + soft-delete. Format: accounts/{account} + Example: "accounts/100" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAccountRequest): + request = analytics_admin.DeleteAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_account] + + # Certain fields should be provided within 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 update_account(self, + request: Optional[Union[analytics_admin.UpdateAccountRequest, dict]] = None, + *, + account: Optional[resources.Account] = 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]] = (), + ) -> resources.Account: + r"""Updates an account. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAccountRequest, dict]]): + The request object. Request message for UpdateAccount + RPC. + account (:class:`google.analytics.admin_v1alpha.types.Account`): + Required. The account to update. The account's ``name`` + field is used to identify the account. + + This corresponds to the ``account`` 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 list of fields to be updated. Field names + must be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "*" to match + all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Account: + A resource message representing a + Google Analytics account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([account, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAccountRequest): + request = analytics_admin.UpdateAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account is not None: + request.account = account + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account.name", request.account.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 provision_account_ticket(self, + request: Optional[Union[analytics_admin.ProvisionAccountTicketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ProvisionAccountTicketResponse: + r"""Requests a ticket for creating an account. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ProvisionAccountTicketRequest, dict]]): + The request object. Request message for + ProvisionAccountTicket RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ProvisionAccountTicketResponse: + Response message for + ProvisionAccountTicket RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ProvisionAccountTicketRequest): + request = analytics_admin.ProvisionAccountTicketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.provision_account_ticket] + + # 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_account_summaries(self, + request: Optional[Union[analytics_admin.ListAccountSummariesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAccountSummariesAsyncPager: + r"""Returns summaries of all accounts accessible by the + caller. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListAccountSummariesRequest, dict]]): + The request object. Request message for + ListAccountSummaries RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccountSummariesAsyncPager: + Response message for + ListAccountSummaries RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccountSummariesRequest): + request = analytics_admin.ListAccountSummariesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_account_summaries] + + # 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.ListAccountSummariesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_property(self, + request: Optional[Union[analytics_admin.GetPropertyRequest, 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]] = (), + ) -> resources.Property: + r"""Lookup for a single "GA4" Property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetPropertyRequest, dict]]): + The request object. Request message for GetProperty RPC. + name (:class:`str`): + Required. The name of the property to lookup. Format: + properties/{property_id} Example: "properties/1000" + + 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.analytics.admin_v1alpha.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetPropertyRequest): + request = analytics_admin.GetPropertyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_property] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_properties(self, + request: Optional[Union[analytics_admin.ListPropertiesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPropertiesAsyncPager: + r"""Returns child Properties under the specified parent + Account. + Only "GA4" properties will be returned. + Properties will be excluded if the caller does not have + access. Soft-deleted (ie: "trashed") properties are + excluded by default. Returns an empty list if no + relevant properties are found. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListPropertiesRequest, dict]]): + The request object. Request message for ListProperties + RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListPropertiesAsyncPager: + Response message for ListProperties + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListPropertiesRequest): + request = analytics_admin.ListPropertiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_properties] + + # 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.ListPropertiesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_property(self, + request: Optional[Union[analytics_admin.CreatePropertyRequest, dict]] = None, + *, + property: Optional[resources.Property] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Property: + r"""Creates an "GA4" property with the specified location + and attributes. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreatePropertyRequest, dict]]): + The request object. Request message for CreateProperty + RPC. + property (:class:`google.analytics.admin_v1alpha.types.Property`): + Required. The property to create. + Note: the supplied property must specify + its parent. + + This corresponds to the ``property`` 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.analytics.admin_v1alpha.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([property]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreatePropertyRequest): + request = analytics_admin.CreatePropertyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if property is not None: + request.property = property + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_property] + + # 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_property(self, + request: Optional[Union[analytics_admin.DeletePropertyRequest, 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]] = (), + ) -> resources.Property: + r"""Marks target Property as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + properties. However, they can be restored using the + Trash Can UI. + + If the properties are not restored before the expiration + time, the Property and all child resources (eg: + GoogleAdsLinks, Streams, AccessBindings) will be + permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found, or is not a + GA4 Property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeletePropertyRequest, dict]]): + The request object. Request message for DeleteProperty + RPC. + name (:class:`str`): + Required. The name of the Property to soft-delete. + Format: properties/{property_id} Example: + "properties/1000" + + 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.analytics.admin_v1alpha.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeletePropertyRequest): + request = analytics_admin.DeletePropertyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_property] + + # Certain fields should be provided within 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_property(self, + request: Optional[Union[analytics_admin.UpdatePropertyRequest, dict]] = None, + *, + property: Optional[resources.Property] = 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]] = (), + ) -> resources.Property: + r"""Updates a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdatePropertyRequest, dict]]): + The request object. Request message for UpdateProperty + RPC. + property (:class:`google.analytics.admin_v1alpha.types.Property`): + Required. The property to update. The property's + ``name`` field is used to identify the property to be + updated. + + This corresponds to the ``property`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([property, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdatePropertyRequest): + request = analytics_admin.UpdatePropertyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if property is not None: + request.property = property + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_property] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property.name", request.property.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_firebase_link(self, + request: Optional[Union[analytics_admin.CreateFirebaseLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + firebase_link: Optional[resources.FirebaseLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.FirebaseLink: + r"""Creates a FirebaseLink. + + Properties can have at most one FirebaseLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateFirebaseLinkRequest, dict]]): + The request object. Request message for + CreateFirebaseLink RPC + parent (:class:`str`): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firebase_link (:class:`google.analytics.admin_v1alpha.types.FirebaseLink`): + Required. The Firebase link to + create. + + This corresponds to the ``firebase_link`` 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.analytics.admin_v1alpha.types.FirebaseLink: + A link between a GA4 property and a + Firebase project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, firebase_link]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateFirebaseLinkRequest): + request = analytics_admin.CreateFirebaseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if firebase_link is not None: + request.firebase_link = firebase_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_firebase_link] + + # Certain 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 delete_firebase_link(self, + request: Optional[Union[analytics_admin.DeleteFirebaseLinkRequest, 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 FirebaseLink on a property + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteFirebaseLinkRequest, dict]]): + The request object. Request message for + DeleteFirebaseLink RPC + name (:class:`str`): + Required. Format: + properties/{property_id}/firebaseLinks/{firebase_link_id} + + Example: ``properties/1234/firebaseLinks/5678`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteFirebaseLinkRequest): + request = analytics_admin.DeleteFirebaseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_firebase_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_firebase_links(self, + request: Optional[Union[analytics_admin.ListFirebaseLinksRequest, 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.ListFirebaseLinksAsyncPager: + r"""Lists FirebaseLinks on a property. + Properties can have at most one FirebaseLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListFirebaseLinksRequest, dict]]): + The request object. Request message for ListFirebaseLinks + RPC + parent (:class:`str`): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListFirebaseLinksAsyncPager: + Response message for + ListFirebaseLinks RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListFirebaseLinksRequest): + request = analytics_admin.ListFirebaseLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_firebase_links] + + # Certain 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.ListFirebaseLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_global_site_tag(self, + request: Optional[Union[analytics_admin.GetGlobalSiteTagRequest, 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]] = (), + ) -> resources.GlobalSiteTag: + r"""Returns the Site Tag for the specified web stream. + Site Tags are immutable singletons. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetGlobalSiteTagRequest, dict]]): + The request object. Request message for GetGlobalSiteTag + RPC. + name (:class:`str`): + Required. The name of the site tag to lookup. Note that + site tags are singletons and do not have unique IDs. + Format: + properties/{property_id}/dataStreams/{stream_id}/globalSiteTag + + Example: + ``properties/123/dataStreams/456/globalSiteTag`` + + 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.analytics.admin_v1alpha.types.GlobalSiteTag: + Read-only resource with the tag for + sending data from a website to a + DataStream. Only present for web + DataStream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetGlobalSiteTagRequest): + request = analytics_admin.GetGlobalSiteTagRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_global_site_tag] + + # Certain fields should be provided within 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_google_ads_link(self, + request: Optional[Union[analytics_admin.CreateGoogleAdsLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_ads_link: Optional[resources.GoogleAdsLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.GoogleAdsLink: + r"""Creates a GoogleAdsLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateGoogleAdsLinkRequest, dict]]): + The request object. Request message for + CreateGoogleAdsLink RPC + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_ads_link (:class:`google.analytics.admin_v1alpha.types.GoogleAdsLink`): + Required. The GoogleAdsLink to + create. + + This corresponds to the ``google_ads_link`` 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.analytics.admin_v1alpha.types.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, google_ads_link]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateGoogleAdsLinkRequest): + request = analytics_admin.CreateGoogleAdsLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if google_ads_link is not None: + request.google_ads_link = google_ads_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_google_ads_link] + + # Certain 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_google_ads_link(self, + request: Optional[Union[analytics_admin.UpdateGoogleAdsLinkRequest, dict]] = None, + *, + google_ads_link: Optional[resources.GoogleAdsLink] = 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]] = (), + ) -> resources.GoogleAdsLink: + r"""Updates a GoogleAdsLink on a property + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateGoogleAdsLinkRequest, dict]]): + The request object. Request message for + UpdateGoogleAdsLink RPC + google_ads_link (:class:`google.analytics.admin_v1alpha.types.GoogleAdsLink`): + The GoogleAdsLink to update + This corresponds to the ``google_ads_link`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_ads_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateGoogleAdsLinkRequest): + request = analytics_admin.UpdateGoogleAdsLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_ads_link is not None: + request.google_ads_link = google_ads_link + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_google_ads_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_ads_link.name", request.google_ads_link.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_google_ads_link(self, + request: Optional[Union[analytics_admin.DeleteGoogleAdsLinkRequest, 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 GoogleAdsLink on a property + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteGoogleAdsLinkRequest, dict]]): + The request object. Request message for + DeleteGoogleAdsLink RPC. + name (:class:`str`): + Required. Example format: + properties/1234/googleAdsLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteGoogleAdsLinkRequest): + request = analytics_admin.DeleteGoogleAdsLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_google_ads_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_google_ads_links(self, + request: Optional[Union[analytics_admin.ListGoogleAdsLinksRequest, 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.ListGoogleAdsLinksAsyncPager: + r"""Lists GoogleAdsLinks on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListGoogleAdsLinksRequest, dict]]): + The request object. Request message for + ListGoogleAdsLinks RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListGoogleAdsLinksAsyncPager: + Response message for + ListGoogleAdsLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListGoogleAdsLinksRequest): + request = analytics_admin.ListGoogleAdsLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_google_ads_links] + + # Certain 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.ListGoogleAdsLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_data_sharing_settings(self, + request: Optional[Union[analytics_admin.GetDataSharingSettingsRequest, 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]] = (), + ) -> resources.DataSharingSettings: + r"""Get data sharing settings on an account. + Data sharing settings are singletons. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDataSharingSettingsRequest, dict]]): + The request object. Request message for + GetDataSharingSettings RPC. + name (:class:`str`): + Required. The name of the settings to lookup. Format: + accounts/{account}/dataSharingSettings + + Example: ``accounts/1000/dataSharingSettings`` + + 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.analytics.admin_v1alpha.types.DataSharingSettings: + A resource message representing data + sharing settings of a Google Analytics + account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataSharingSettingsRequest): + request = analytics_admin.GetDataSharingSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_data_sharing_settings] + + # Certain fields should be provided within 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_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.GetMeasurementProtocolSecretRequest, 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]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Lookup for a single "GA4" MeasurementProtocolSecret. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetMeasurementProtocolSecretRequest, dict]]): + The request object. Request message for + GetMeasurementProtocolSecret RPC. + name (:class:`str`): + Required. The name of the measurement + protocol secret to lookup. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + + 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.analytics.admin_v1alpha.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetMeasurementProtocolSecretRequest): + request = analytics_admin.GetMeasurementProtocolSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_measurement_protocol_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_measurement_protocol_secrets(self, + request: Optional[Union[analytics_admin.ListMeasurementProtocolSecretsRequest, 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.ListMeasurementProtocolSecretsAsyncPager: + r"""Returns child MeasurementProtocolSecrets under the + specified parent Property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsRequest, dict]]): + The request object. Request message for + ListMeasurementProtocolSecret RPC + parent (:class:`str`): + Required. The resource name of the + parent stream. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListMeasurementProtocolSecretsAsyncPager: + Response message for + ListMeasurementProtocolSecret RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListMeasurementProtocolSecretsRequest): + request = analytics_admin.ListMeasurementProtocolSecretsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_measurement_protocol_secrets] + + # Certain 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.ListMeasurementProtocolSecretsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.CreateMeasurementProtocolSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + measurement_protocol_secret: Optional[resources.MeasurementProtocolSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Creates a measurement protocol secret. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateMeasurementProtocolSecretRequest, dict]]): + The request object. Request message for + CreateMeasurementProtocolSecret RPC + parent (:class:`str`): + Required. The parent resource where + this secret will be created. Format: + properties/{property}/dataStreams/{dataStream} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + measurement_protocol_secret (:class:`google.analytics.admin_v1alpha.types.MeasurementProtocolSecret`): + Required. The measurement protocol + secret to create. + + This corresponds to the ``measurement_protocol_secret`` 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.analytics.admin_v1alpha.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, measurement_protocol_secret]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateMeasurementProtocolSecretRequest): + request = analytics_admin.CreateMeasurementProtocolSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if measurement_protocol_secret is not None: + request.measurement_protocol_secret = measurement_protocol_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_measurement_protocol_secret] + + # Certain 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 delete_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.DeleteMeasurementProtocolSecretRequest, 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 target MeasurementProtocolSecret. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteMeasurementProtocolSecretRequest, dict]]): + The request object. Request message for + DeleteMeasurementProtocolSecret RPC + name (:class:`str`): + Required. The name of the + MeasurementProtocolSecret to delete. + Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteMeasurementProtocolSecretRequest): + request = analytics_admin.DeleteMeasurementProtocolSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_measurement_protocol_secret] + + # Certain fields should be provided within 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 update_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.UpdateMeasurementProtocolSecretRequest, dict]] = None, + *, + measurement_protocol_secret: Optional[resources.MeasurementProtocolSecret] = 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]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Updates a measurement protocol secret. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateMeasurementProtocolSecretRequest, dict]]): + The request object. Request message for + UpdateMeasurementProtocolSecret RPC + measurement_protocol_secret (:class:`google.analytics.admin_v1alpha.types.MeasurementProtocolSecret`): + Required. The measurement protocol + secret to update. + + This corresponds to the ``measurement_protocol_secret`` 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 list of fields to be + updated. Omitted fields will not be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([measurement_protocol_secret, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateMeasurementProtocolSecretRequest): + request = analytics_admin.UpdateMeasurementProtocolSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if measurement_protocol_secret is not None: + request.measurement_protocol_secret = measurement_protocol_secret + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_measurement_protocol_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("measurement_protocol_secret.name", request.measurement_protocol_secret.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 acknowledge_user_data_collection(self, + request: Optional[Union[analytics_admin.AcknowledgeUserDataCollectionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.AcknowledgeUserDataCollectionResponse: + r"""Acknowledges the terms of user data collection for + the specified property. + This acknowledgement must be completed (either in the + Google Analytics UI or through this API) before + MeasurementProtocolSecret resources may be created. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.AcknowledgeUserDataCollectionRequest, dict]]): + The request object. Request message for + AcknowledgeUserDataCollection RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AcknowledgeUserDataCollectionResponse: + Response message for + AcknowledgeUserDataCollection RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.AcknowledgeUserDataCollectionRequest): + request = analytics_admin.AcknowledgeUserDataCollectionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.acknowledge_user_data_collection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # 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_sk_ad_network_conversion_value_schema(self, + request: Optional[Union[analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, 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]] = (), + ) -> resources.SKAdNetworkConversionValueSchema: + r"""Looks up a single SKAdNetworkConversionValueSchema. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetSKAdNetworkConversionValueSchemaRequest, dict]]): + The request object. Request message for + GetSKAdNetworkConversionValueSchema RPC. + name (:class:`str`): + Required. The resource name of SKAdNetwork conversion + value schema to look up. Format: + properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} + + 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.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema: + SKAdNetwork conversion value schema + of an iOS stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetSKAdNetworkConversionValueSchemaRequest): + request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_sk_ad_network_conversion_value_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_sk_ad_network_conversion_value_schema(self, + request: Optional[Union[analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + skadnetwork_conversion_value_schema: Optional[resources.SKAdNetworkConversionValueSchema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SKAdNetworkConversionValueSchema: + r"""Creates a SKAdNetworkConversionValueSchema. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateSKAdNetworkConversionValueSchemaRequest, dict]]): + The request object. Request message for + CreateSKAdNetworkConversionValueSchema + RPC. + parent (:class:`str`): + Required. The parent resource where + this schema will be created. Format: + properties/{property}/dataStreams/{dataStream} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + skadnetwork_conversion_value_schema (:class:`google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema`): + Required. SKAdNetwork conversion + value schema to create. + + This corresponds to the ``skadnetwork_conversion_value_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema: + SKAdNetwork conversion value schema + of an iOS stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, skadnetwork_conversion_value_schema]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest): + request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if skadnetwork_conversion_value_schema is not None: + request.skadnetwork_conversion_value_schema = skadnetwork_conversion_value_schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_sk_ad_network_conversion_value_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_sk_ad_network_conversion_value_schema(self, + request: Optional[Union[analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, 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 target SKAdNetworkConversionValueSchema. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteSKAdNetworkConversionValueSchemaRequest, dict]]): + The request object. Request message for + DeleteSKAdNetworkConversionValueSchema + RPC. + name (:class:`str`): + Required. The name of the + SKAdNetworkConversionValueSchema to delete. Format: + properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest): + request = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_sk_ad_network_conversion_value_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_sk_ad_network_conversion_value_schema(self, + request: Optional[Union[analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, dict]] = None, + *, + skadnetwork_conversion_value_schema: Optional[resources.SKAdNetworkConversionValueSchema] = 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]] = (), + ) -> resources.SKAdNetworkConversionValueSchema: + r"""Updates a SKAdNetworkConversionValueSchema. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateSKAdNetworkConversionValueSchemaRequest, dict]]): + The request object. Request message for + UpdateSKAdNetworkConversionValueSchema + RPC. + skadnetwork_conversion_value_schema (:class:`google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema`): + Required. SKAdNetwork conversion + value schema to update. + + This corresponds to the ``skadnetwork_conversion_value_schema`` 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 list of fields to be + updated. Omitted fields will not be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema: + SKAdNetwork conversion value schema + of an iOS stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([skadnetwork_conversion_value_schema, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest): + request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if skadnetwork_conversion_value_schema is not None: + request.skadnetwork_conversion_value_schema = skadnetwork_conversion_value_schema + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_sk_ad_network_conversion_value_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("skadnetwork_conversion_value_schema.name", request.skadnetwork_conversion_value_schema.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sk_ad_network_conversion_value_schemas(self, + request: Optional[Union[analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, 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.ListSKAdNetworkConversionValueSchemasAsyncPager: + r"""Lists SKAdNetworkConversionValueSchema on a stream. + Properties can have at most one + SKAdNetworkConversionValueSchema. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasRequest, dict]]): + The request object. Request message for + ListSKAdNetworkConversionValueSchemas + RPC + parent (:class:`str`): + Required. The DataStream resource to list schemas for. + Format: + properties/{property_id}/dataStreams/{dataStream} + Example: properties/1234/dataStreams/5678 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSKAdNetworkConversionValueSchemasAsyncPager: + Response message for + ListSKAdNetworkConversionValueSchemas + RPC Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListSKAdNetworkConversionValueSchemasRequest): + request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_sk_ad_network_conversion_value_schemas] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSKAdNetworkConversionValueSchemasAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_change_history_events(self, + request: Optional[Union[analytics_admin.SearchChangeHistoryEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchChangeHistoryEventsAsyncPager: + r"""Searches through all changes to an account or its + children given the specified set of filters. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsRequest, dict]]): + The request object. Request message for + SearchChangeHistoryEvents RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.SearchChangeHistoryEventsAsyncPager: + Response message for SearchAccounts + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.SearchChangeHistoryEventsRequest): + request = analytics_admin.SearchChangeHistoryEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_change_history_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account", request.account), + )), + ) + + # 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.SearchChangeHistoryEventsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_google_signals_settings(self, + request: Optional[Union[analytics_admin.GetGoogleSignalsSettingsRequest, 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]] = (), + ) -> resources.GoogleSignalsSettings: + r"""Lookup for Google Signals settings for a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetGoogleSignalsSettingsRequest, dict]]): + The request object. Request message for + GetGoogleSignalsSettings RPC + name (:class:`str`): + Required. The name of the google + signals settings to retrieve. Format: + properties/{property}/googleSignalsSettings + + 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.analytics.admin_v1alpha.types.GoogleSignalsSettings: + Settings values for Google Signals. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetGoogleSignalsSettingsRequest): + request = analytics_admin.GetGoogleSignalsSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_google_signals_settings] + + # Certain fields should be provided within 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_google_signals_settings(self, + request: Optional[Union[analytics_admin.UpdateGoogleSignalsSettingsRequest, dict]] = None, + *, + google_signals_settings: Optional[resources.GoogleSignalsSettings] = 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]] = (), + ) -> resources.GoogleSignalsSettings: + r"""Updates Google Signals settings for a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateGoogleSignalsSettingsRequest, dict]]): + The request object. Request message for + UpdateGoogleSignalsSettings RPC + google_signals_settings (:class:`google.analytics.admin_v1alpha.types.GoogleSignalsSettings`): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``google_signals_settings`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.GoogleSignalsSettings: + Settings values for Google Signals. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_signals_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateGoogleSignalsSettingsRequest): + request = analytics_admin.UpdateGoogleSignalsSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_signals_settings is not None: + request.google_signals_settings = google_signals_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_google_signals_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_signals_settings.name", request.google_signals_settings.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_conversion_event(self, + request: Optional[Union[analytics_admin.CreateConversionEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversion_event: Optional[resources.ConversionEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateConversionEventRequest, dict]]): + The request object. Request message for + CreateConversionEvent RPC + parent (:class:`str`): + Required. The resource name of the + parent property where this conversion + event will be created. Format: + properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversion_event (:class:`google.analytics.admin_v1alpha.types.ConversionEvent`): + Required. The conversion event to + create. + + This corresponds to the ``conversion_event`` 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.analytics.admin_v1alpha.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.create_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversion_event]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateConversionEventRequest): + request = analytics_admin.CreateConversionEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversion_event is not None: + request.conversion_event = conversion_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_conversion_event(self, + request: Optional[Union[analytics_admin.UpdateConversionEventRequest, dict]] = None, + *, + conversion_event: Optional[resources.ConversionEvent] = 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]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateConversionEventRequest, dict]]): + The request object. Request message for + UpdateConversionEvent RPC + conversion_event (:class:`google.analytics.admin_v1alpha.types.ConversionEvent`): + Required. The conversion event to update. The ``name`` + field is used to identify the settings to be updated. + + This corresponds to the ``conversion_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.update_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversion_event, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateConversionEventRequest): + request = analytics_admin.UpdateConversionEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversion_event is not None: + request.conversion_event = conversion_event + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversion_event.name", request.conversion_event.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_conversion_event(self, + request: Optional[Union[analytics_admin.GetConversionEventRequest, 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]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetConversionEventRequest, dict]]): + The request object. Request message for + GetConversionEvent RPC + name (:class:`str`): + Required. The resource name of the conversion event to + retrieve. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456" + + 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.analytics.admin_v1alpha.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.get_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetConversionEventRequest): + request = analytics_admin.GetConversionEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_conversion_event(self, + request: Optional[Union[analytics_admin.DeleteConversionEventRequest, 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"""Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteConversionEventRequest, dict]]): + The request object. Request message for + DeleteConversionEvent RPC + name (:class:`str`): + Required. The resource name of the conversion event to + delete. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456" + + 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. + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.delete_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteConversionEventRequest): + request = analytics_admin.DeleteConversionEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_conversion_events(self, + request: Optional[Union[analytics_admin.ListConversionEventsRequest, 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.ListConversionEventsAsyncPager: + r"""Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + + Returns an empty list if no conversion events are found. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListConversionEventsRequest, dict]]): + The request object. Request message for + ListConversionEvents RPC + parent (:class:`str`): + Required. The resource name of the + parent property. Example: + 'properties/123' + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListConversionEventsAsyncPager: + Response message for + ListConversionEvents RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.list_conversion_events is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListConversionEventsRequest): + request = analytics_admin.ListConversionEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_conversion_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversionEventsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_key_event(self, + request: Optional[Union[analytics_admin.CreateKeyEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + key_event: Optional[resources.KeyEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyEvent: + r"""Creates a Key Event. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateKeyEventRequest, dict]]): + The request object. Request message for CreateKeyEvent + RPC + parent (:class:`str`): + Required. The resource name of the + parent property where this Key Event + will be created. Format: properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_event (:class:`google.analytics.admin_v1alpha.types.KeyEvent`): + Required. The Key Event to create. + This corresponds to the ``key_event`` 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.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, key_event]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateKeyEventRequest): + request = analytics_admin.CreateKeyEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_event is not None: + request.key_event = key_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_key_event(self, + request: Optional[Union[analytics_admin.UpdateKeyEventRequest, dict]] = None, + *, + key_event: Optional[resources.KeyEvent] = 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]] = (), + ) -> resources.KeyEvent: + r"""Updates a Key Event. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateKeyEventRequest, dict]]): + The request object. Request message for UpdateKeyEvent + RPC + key_event (:class:`google.analytics.admin_v1alpha.types.KeyEvent`): + Required. The Key Event to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``key_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([key_event, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateKeyEventRequest): + request = analytics_admin.UpdateKeyEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if key_event is not None: + request.key_event = key_event + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("key_event.name", request.key_event.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_key_event(self, + request: Optional[Union[analytics_admin.GetKeyEventRequest, 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]] = (), + ) -> resources.KeyEvent: + r"""Retrieve a single Key Event. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetKeyEventRequest, dict]]): + The request object. Request message for GetKeyEvent RPC + name (:class:`str`): + Required. The resource name of the Key Event to + retrieve. Format: + properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456" + + 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.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetKeyEventRequest): + request = analytics_admin.GetKeyEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_key_event(self, + request: Optional[Union[analytics_admin.DeleteKeyEventRequest, 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 Key Event. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteKeyEventRequest, dict]]): + The request object. Request message for DeleteKeyEvent + RPC + name (:class:`str`): + Required. The resource name of the Key Event to delete. + Format: properties/{property}/keyEvents/{key_event} + Example: "properties/123/keyEvents/456" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteKeyEventRequest): + request = analytics_admin.DeleteKeyEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_key_events(self, + request: Optional[Union[analytics_admin.ListKeyEventsRequest, 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.ListKeyEventsAsyncPager: + r"""Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListKeyEventsRequest, dict]]): + The request object. Request message for ListKeyEvents RPC + parent (:class:`str`): + Required. The resource name of the + parent property. Example: + 'properties/123' + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListKeyEventsAsyncPager: + Response message for ListKeyEvents + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListKeyEventsRequest): + request = analytics_admin.ListKeyEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_key_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListKeyEventsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_display_video360_advertiser_link(self, + request: Optional[Union[analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, 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]] = (), + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Look up a single DisplayVideo360AdvertiserLink + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkRequest, dict]]): + The request object. Request message for + GetDisplayVideo360AdvertiserLink RPC. + name (:class:`str`): + Required. The name of the + DisplayVideo360AdvertiserLink to get. + Example format: + properties/1234/displayVideo360AdvertiserLink/5678 + + 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.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDisplayVideo360AdvertiserLinkRequest): + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_display_video360_advertiser_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_display_video360_advertiser_links(self, + request: Optional[Union[analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, 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.ListDisplayVideo360AdvertiserLinksAsyncPager: + r"""Lists all DisplayVideo360AdvertiserLinks on a + property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksRequest, dict]]): + The request object. Request message for + ListDisplayVideo360AdvertiserLinks RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinksAsyncPager: + Response message for + ListDisplayVideo360AdvertiserLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListDisplayVideo360AdvertiserLinksRequest): + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_display_video360_advertiser_links] + + # Certain 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.ListDisplayVideo360AdvertiserLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_display_video360_advertiser_link(self, + request: Optional[Union[analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + display_video_360_advertiser_link: Optional[resources.DisplayVideo360AdvertiserLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Creates a DisplayVideo360AdvertiserLink. + This can only be utilized by users who have proper + authorization both on the Google Analytics property and + on the Display & Video 360 advertiser. Users who do not + have access to the Display & Video 360 advertiser should + instead seek to create a DisplayVideo360LinkProposal. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkRequest, dict]]): + The request object. Request message for + CreateDisplayVideo360AdvertiserLink RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_video_360_advertiser_link (:class:`google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink`): + Required. The + DisplayVideo360AdvertiserLink to create. + + This corresponds to the ``display_video_360_advertiser_link`` 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.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, display_video_360_advertiser_link]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest): + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if display_video_360_advertiser_link is not None: + request.display_video_360_advertiser_link = display_video_360_advertiser_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_display_video360_advertiser_link] + + # Certain 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 delete_display_video360_advertiser_link(self, + request: Optional[Union[analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, 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 DisplayVideo360AdvertiserLink on a + property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkRequest, dict]]): + The request object. Request message for + DeleteDisplayVideo360AdvertiserLink RPC. + name (:class:`str`): + Required. The name of the + DisplayVideo360AdvertiserLink to delete. + Example format: + properties/1234/displayVideo360AdvertiserLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest): + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_display_video360_advertiser_link] + + # Certain fields should be provided within 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 update_display_video360_advertiser_link(self, + request: Optional[Union[analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, dict]] = None, + *, + display_video_360_advertiser_link: Optional[resources.DisplayVideo360AdvertiserLink] = 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]] = (), + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Updates a DisplayVideo360AdvertiserLink on a + property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDisplayVideo360AdvertiserLinkRequest, dict]]): + The request object. Request message for + UpdateDisplayVideo360AdvertiserLink RPC. + display_video_360_advertiser_link (:class:`google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink`): + The DisplayVideo360AdvertiserLink to + update + + This corresponds to the ``display_video_360_advertiser_link`` 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 list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([display_video_360_advertiser_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest): + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if display_video_360_advertiser_link is not None: + request.display_video_360_advertiser_link = display_video_360_advertiser_link + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_display_video360_advertiser_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("display_video_360_advertiser_link.name", request.display_video_360_advertiser_link.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_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, 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]] = (), + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Lookup for a single + DisplayVideo360AdvertiserLinkProposal. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + The request object. Request message for + GetDisplayVideo360AdvertiserLinkProposal + RPC. + name (:class:`str`): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to + get. Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + + 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.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_display_video360_advertiser_link_proposal] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_display_video360_advertiser_link_proposals(self, + request: Optional[Union[analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, 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.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager: + r"""Lists DisplayVideo360AdvertiserLinkProposals on a + property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict]]): + The request object. Request message for + ListDisplayVideo360AdvertiserLinkProposals + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager: + Response message for + ListDisplayVideo360AdvertiserLinkProposals + RPC. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest): + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_display_video360_advertiser_link_proposals] + + # Certain 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.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict]] = None, + *, + parent: Optional[str] = None, + display_video_360_advertiser_link_proposal: Optional[resources.DisplayVideo360AdvertiserLinkProposal] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Creates a DisplayVideo360AdvertiserLinkProposal. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + The request object. Request message for + CreateDisplayVideo360AdvertiserLinkProposal + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_video_360_advertiser_link_proposal (:class:`google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal`): + Required. The + DisplayVideo360AdvertiserLinkProposal to + create. + + This corresponds to the ``display_video_360_advertiser_link_proposal`` 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.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, display_video_360_advertiser_link_proposal]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if display_video_360_advertiser_link_proposal is not None: + request.display_video_360_advertiser_link_proposal = display_video_360_advertiser_link_proposal + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_display_video360_advertiser_link_proposal] + + # Certain 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 delete_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, 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 DisplayVideo360AdvertiserLinkProposal on a + property. This can only be used on cancelled proposals. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + The request object. Request message for + DeleteDisplayVideo360AdvertiserLinkProposal + RPC. + name (:class:`str`): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to + delete. Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_display_video360_advertiser_link_proposal] + + # Certain fields should be provided within 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 approve_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + r"""Approves a DisplayVideo360AdvertiserLinkProposal. + The DisplayVideo360AdvertiserLinkProposal will be + deleted and a new DisplayVideo360AdvertiserLink will be + created. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + The request object. Request message for + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + Response message for + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.approve_display_video360_advertiser_link_proposal] + + # Certain fields should be provided within 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 cancel_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Cancels a DisplayVideo360AdvertiserLinkProposal. + Cancelling can mean either: + + - Declining a proposal initiated from Display & Video + 360 + - Withdrawing a proposal initiated from Google Analytics + After being cancelled, a proposal will eventually be + deleted automatically. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict]]): + The request object. Request message for + CancelDisplayVideo360AdvertiserLinkProposal + RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.cancel_display_video360_advertiser_link_proposal] + + # Certain fields should be provided within 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_custom_dimension(self, + request: Optional[Union[analytics_admin.CreateCustomDimensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_dimension: Optional[resources.CustomDimension] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CustomDimension: + r"""Creates a CustomDimension. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateCustomDimensionRequest, dict]]): + The request object. Request message for + CreateCustomDimension RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_dimension (:class:`google.analytics.admin_v1alpha.types.CustomDimension`): + Required. The CustomDimension to + create. + + This corresponds to the ``custom_dimension`` 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.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_dimension]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCustomDimensionRequest): + request = analytics_admin.CreateCustomDimensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_dimension is not None: + request.custom_dimension = custom_dimension + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_custom_dimension] + + # Certain 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_custom_dimension(self, + request: Optional[Union[analytics_admin.UpdateCustomDimensionRequest, dict]] = None, + *, + custom_dimension: Optional[resources.CustomDimension] = 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]] = (), + ) -> resources.CustomDimension: + r"""Updates a CustomDimension on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateCustomDimensionRequest, dict]]): + The request object. Request message for + UpdateCustomDimension RPC. + custom_dimension (:class:`google.analytics.admin_v1alpha.types.CustomDimension`): + The CustomDimension to update + This corresponds to the ``custom_dimension`` 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 list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_dimension, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCustomDimensionRequest): + request = analytics_admin.UpdateCustomDimensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_dimension is not None: + request.custom_dimension = custom_dimension + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_custom_dimension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("custom_dimension.name", request.custom_dimension.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_custom_dimensions(self, + request: Optional[Union[analytics_admin.ListCustomDimensionsRequest, 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.ListCustomDimensionsAsyncPager: + r"""Lists CustomDimensions on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListCustomDimensionsRequest, dict]]): + The request object. Request message for + ListCustomDimensions RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomDimensionsAsyncPager: + Response message for + ListCustomDimensions RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCustomDimensionsRequest): + request = analytics_admin.ListCustomDimensionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_custom_dimensions] + + # Certain 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.ListCustomDimensionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def archive_custom_dimension(self, + request: Optional[Union[analytics_admin.ArchiveCustomDimensionRequest, 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"""Archives a CustomDimension on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ArchiveCustomDimensionRequest, dict]]): + The request object. Request message for + ArchiveCustomDimension RPC. + name (:class:`str`): + Required. The name of the + CustomDimension to archive. Example + format: + properties/1234/customDimensions/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveCustomDimensionRequest): + request = analytics_admin.ArchiveCustomDimensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.archive_custom_dimension] + + # Certain fields should be provided within 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_custom_dimension(self, + request: Optional[Union[analytics_admin.GetCustomDimensionRequest, 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]] = (), + ) -> resources.CustomDimension: + r"""Lookup for a single CustomDimension. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetCustomDimensionRequest, dict]]): + The request object. Request message for + GetCustomDimension RPC. + name (:class:`str`): + Required. The name of the + CustomDimension to get. Example format: + properties/1234/customDimensions/5678 + + 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.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCustomDimensionRequest): + request = analytics_admin.GetCustomDimensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_custom_dimension] + + # Certain fields should be provided within 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_custom_metric(self, + request: Optional[Union[analytics_admin.CreateCustomMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_metric: Optional[resources.CustomMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CustomMetric: + r"""Creates a CustomMetric. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateCustomMetricRequest, dict]]): + The request object. Request message for + CreateCustomMetric RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_metric (:class:`google.analytics.admin_v1alpha.types.CustomMetric`): + Required. The CustomMetric to create. + This corresponds to the ``custom_metric`` 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.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_metric]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCustomMetricRequest): + request = analytics_admin.CreateCustomMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_metric is not None: + request.custom_metric = custom_metric + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_custom_metric] + + # Certain 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_custom_metric(self, + request: Optional[Union[analytics_admin.UpdateCustomMetricRequest, dict]] = None, + *, + custom_metric: Optional[resources.CustomMetric] = 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]] = (), + ) -> resources.CustomMetric: + r"""Updates a CustomMetric on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateCustomMetricRequest, dict]]): + The request object. Request message for + UpdateCustomMetric RPC. + custom_metric (:class:`google.analytics.admin_v1alpha.types.CustomMetric`): + The CustomMetric to update + This corresponds to the ``custom_metric`` 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 list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_metric, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCustomMetricRequest): + request = analytics_admin.UpdateCustomMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_metric is not None: + request.custom_metric = custom_metric + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_custom_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("custom_metric.name", request.custom_metric.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_custom_metrics(self, + request: Optional[Union[analytics_admin.ListCustomMetricsRequest, 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.ListCustomMetricsAsyncPager: + r"""Lists CustomMetrics on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListCustomMetricsRequest, dict]]): + The request object. Request message for ListCustomMetrics + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomMetricsAsyncPager: + Response message for + ListCustomMetrics RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCustomMetricsRequest): + request = analytics_admin.ListCustomMetricsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_custom_metrics] + + # Certain 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.ListCustomMetricsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def archive_custom_metric(self, + request: Optional[Union[analytics_admin.ArchiveCustomMetricRequest, 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"""Archives a CustomMetric on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ArchiveCustomMetricRequest, dict]]): + The request object. Request message for + ArchiveCustomMetric RPC. + name (:class:`str`): + Required. The name of the + CustomMetric to archive. Example format: + properties/1234/customMetrics/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveCustomMetricRequest): + request = analytics_admin.ArchiveCustomMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.archive_custom_metric] + + # Certain fields should be provided within 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_custom_metric(self, + request: Optional[Union[analytics_admin.GetCustomMetricRequest, 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]] = (), + ) -> resources.CustomMetric: + r"""Lookup for a single CustomMetric. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetCustomMetricRequest, dict]]): + The request object. Request message for GetCustomMetric + RPC. + name (:class:`str`): + Required. The name of the + CustomMetric to get. Example format: + properties/1234/customMetrics/5678 + + 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.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCustomMetricRequest): + request = analytics_admin.GetCustomMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_custom_metric] + + # Certain fields should be provided within 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_data_retention_settings(self, + request: Optional[Union[analytics_admin.GetDataRetentionSettingsRequest, 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]] = (), + ) -> resources.DataRetentionSettings: + r"""Returns the singleton data retention settings for + this property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDataRetentionSettingsRequest, dict]]): + The request object. Request message for + GetDataRetentionSettings RPC. + name (:class:`str`): + Required. The name of the settings to + lookup. Format: + + properties/{property}/dataRetentionSettings + Example: + "properties/1000/dataRetentionSettings" + + 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.analytics.admin_v1alpha.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataRetentionSettingsRequest): + request = analytics_admin.GetDataRetentionSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_data_retention_settings] + + # Certain fields should be provided within 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_data_retention_settings(self, + request: Optional[Union[analytics_admin.UpdateDataRetentionSettingsRequest, dict]] = None, + *, + data_retention_settings: Optional[resources.DataRetentionSettings] = 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]] = (), + ) -> resources.DataRetentionSettings: + r"""Updates the singleton data retention settings for + this property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDataRetentionSettingsRequest, dict]]): + The request object. Request message for + UpdateDataRetentionSettings RPC. + data_retention_settings (:class:`google.analytics.admin_v1alpha.types.DataRetentionSettings`): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``data_retention_settings`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_retention_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataRetentionSettingsRequest): + request = analytics_admin.UpdateDataRetentionSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_retention_settings is not None: + request.data_retention_settings = data_retention_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_data_retention_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_retention_settings.name", request.data_retention_settings.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_data_stream(self, + request: Optional[Union[analytics_admin.CreateDataStreamRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_stream: Optional[resources.DataStream] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DataStream: + r"""Creates a DataStream. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateDataStreamRequest, dict]]): + The request object. Request message for CreateDataStream + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_stream (:class:`google.analytics.admin_v1alpha.types.DataStream`): + Required. The DataStream to create. + This corresponds to the ``data_stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_stream]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateDataStreamRequest): + request = analytics_admin.CreateDataStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_stream is not None: + request.data_stream = data_stream + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_data_stream(self, + request: Optional[Union[analytics_admin.DeleteDataStreamRequest, 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 DataStream on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteDataStreamRequest, dict]]): + The request object. Request message for DeleteDataStream + RPC. + name (:class:`str`): + Required. The name of the DataStream + to delete. Example format: + properties/1234/dataStreams/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteDataStreamRequest): + request = analytics_admin.DeleteDataStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_data_stream(self, + request: Optional[Union[analytics_admin.UpdateDataStreamRequest, dict]] = None, + *, + data_stream: Optional[resources.DataStream] = 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]] = (), + ) -> resources.DataStream: + r"""Updates a DataStream on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDataStreamRequest, dict]]): + The request object. Request message for UpdateDataStream + RPC. + data_stream (:class:`google.analytics.admin_v1alpha.types.DataStream`): + The DataStream to update + This corresponds to the ``data_stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_stream, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataStreamRequest): + request = analytics_admin.UpdateDataStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_stream is not None: + request.data_stream = data_stream + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_stream.name", request.data_stream.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_data_streams(self, + request: Optional[Union[analytics_admin.ListDataStreamsRequest, 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.ListDataStreamsAsyncPager: + r"""Lists DataStreams on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListDataStreamsRequest, dict]]): + The request object. Request message for ListDataStreams + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDataStreamsAsyncPager: + Response message for ListDataStreams + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListDataStreamsRequest): + request = analytics_admin.ListDataStreamsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_data_streams] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDataStreamsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_data_stream(self, + request: Optional[Union[analytics_admin.GetDataStreamRequest, 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]] = (), + ) -> resources.DataStream: + r"""Lookup for a single DataStream. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDataStreamRequest, dict]]): + The request object. Request message for GetDataStream + RPC. + name (:class:`str`): + Required. The name of the DataStream + to get. Example format: + properties/1234/dataStreams/5678 + + 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.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataStreamRequest): + request = analytics_admin.GetDataStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_audience(self, + request: Optional[Union[analytics_admin.GetAudienceRequest, 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]] = (), + ) -> audience.Audience: + r"""Lookup for a single Audience. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetAudienceRequest, dict]]): + The request object. Request message for GetAudience RPC. + name (:class:`str`): + Required. The name of the Audience to + get. Example format: + properties/1234/audiences/5678 + + 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.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAudienceRequest): + request = analytics_admin.GetAudienceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_audience] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_audiences(self, + request: Optional[Union[analytics_admin.ListAudiencesRequest, 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.ListAudiencesAsyncPager: + r"""Lists Audiences on a property. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListAudiencesRequest, dict]]): + The request object. Request message for ListAudiences + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAudiencesAsyncPager: + Response message for ListAudiences + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAudiencesRequest): + request = analytics_admin.ListAudiencesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_audiences] + + # Certain 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.ListAudiencesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_audience(self, + request: Optional[Union[analytics_admin.CreateAudienceRequest, dict]] = None, + *, + parent: Optional[str] = None, + audience: Optional[gaa_audience.Audience] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gaa_audience.Audience: + r"""Creates an Audience. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateAudienceRequest, dict]]): + The request object. Request message for CreateAudience + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audience (:class:`google.analytics.admin_v1alpha.types.Audience`): + Required. The audience to create. + This corresponds to the ``audience`` 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.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, audience]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateAudienceRequest): + request = analytics_admin.CreateAudienceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if audience is not None: + request.audience = audience + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_audience] + + # Certain 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_audience(self, + request: Optional[Union[analytics_admin.UpdateAudienceRequest, dict]] = None, + *, + audience: Optional[gaa_audience.Audience] = 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]] = (), + ) -> gaa_audience.Audience: + r"""Updates an Audience on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAudienceRequest, dict]]): + The request object. Request message for UpdateAudience + RPC. + audience (:class:`google.analytics.admin_v1alpha.types.Audience`): + Required. The audience to update. The audience's + ``name`` field is used to identify the audience to be + updated. + + This corresponds to the ``audience`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([audience, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAudienceRequest): + request = analytics_admin.UpdateAudienceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if audience is not None: + request.audience = audience + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_audience] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("audience.name", request.audience.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 archive_audience(self, + request: Optional[Union[analytics_admin.ArchiveAudienceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Archives an Audience on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ArchiveAudienceRequest, dict]]): + The request object. Request message for ArchiveAudience + RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveAudienceRequest): + request = analytics_admin.ArchiveAudienceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.archive_audience] + + # Certain fields should be provided within 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_search_ads360_link(self, + request: Optional[Union[analytics_admin.GetSearchAds360LinkRequest, 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]] = (), + ) -> resources.SearchAds360Link: + r"""Look up a single SearchAds360Link + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetSearchAds360LinkRequest, dict]]): + The request object. Request message for + GetSearchAds360Link RPC. + name (:class:`str`): + Required. The name of the + SearchAds360Link to get. Example format: + properties/1234/SearchAds360Link/5678 + + 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.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetSearchAds360LinkRequest): + request = analytics_admin.GetSearchAds360LinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_search_ads360_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_search_ads360_links(self, + request: Optional[Union[analytics_admin.ListSearchAds360LinksRequest, 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.ListSearchAds360LinksAsyncPager: + r"""Lists all SearchAds360Links on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListSearchAds360LinksRequest, dict]]): + The request object. Request message for + ListSearchAds360Links RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSearchAds360LinksAsyncPager: + Response message for + ListSearchAds360Links RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListSearchAds360LinksRequest): + request = analytics_admin.ListSearchAds360LinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_search_ads360_links] + + # Certain 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.ListSearchAds360LinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_search_ads360_link(self, + request: Optional[Union[analytics_admin.CreateSearchAds360LinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + search_ads_360_link: Optional[resources.SearchAds360Link] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SearchAds360Link: + r"""Creates a SearchAds360Link. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateSearchAds360LinkRequest, dict]]): + The request object. Request message for + CreateSearchAds360Link RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_ads_360_link (:class:`google.analytics.admin_v1alpha.types.SearchAds360Link`): + Required. The SearchAds360Link to + create. + + This corresponds to the ``search_ads_360_link`` 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.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, search_ads_360_link]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateSearchAds360LinkRequest): + request = analytics_admin.CreateSearchAds360LinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if search_ads_360_link is not None: + request.search_ads_360_link = search_ads_360_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_search_ads360_link] + + # Certain 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 delete_search_ads360_link(self, + request: Optional[Union[analytics_admin.DeleteSearchAds360LinkRequest, 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 SearchAds360Link on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteSearchAds360LinkRequest, dict]]): + The request object. Request message for + DeleteSearchAds360Link RPC. + name (:class:`str`): + Required. The name of the + SearchAds360Link to delete. Example + format: + properties/1234/SearchAds360Links/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteSearchAds360LinkRequest): + request = analytics_admin.DeleteSearchAds360LinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_search_ads360_link] + + # Certain fields should be provided within 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 update_search_ads360_link(self, + request: Optional[Union[analytics_admin.UpdateSearchAds360LinkRequest, dict]] = None, + *, + search_ads_360_link: Optional[resources.SearchAds360Link] = 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]] = (), + ) -> resources.SearchAds360Link: + r"""Updates a SearchAds360Link on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateSearchAds360LinkRequest, dict]]): + The request object. Request message for + UpdateSearchAds360Link RPC. + search_ads_360_link (:class:`google.analytics.admin_v1alpha.types.SearchAds360Link`): + The SearchAds360Link to update + This corresponds to the ``search_ads_360_link`` 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 list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([search_ads_360_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateSearchAds360LinkRequest): + request = analytics_admin.UpdateSearchAds360LinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if search_ads_360_link is not None: + request.search_ads_360_link = search_ads_360_link + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_search_ads360_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("search_ads_360_link.name", request.search_ads_360_link.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_attribution_settings(self, + request: Optional[Union[analytics_admin.GetAttributionSettingsRequest, 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]] = (), + ) -> resources.AttributionSettings: + r"""Lookup for a AttributionSettings singleton. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetAttributionSettingsRequest, dict]]): + The request object. Request message for + GetAttributionSettings RPC. + name (:class:`str`): + Required. The name of the attribution + settings to retrieve. Format: + properties/{property}/attributionSettings + + 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.analytics.admin_v1alpha.types.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAttributionSettingsRequest): + request = analytics_admin.GetAttributionSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_attribution_settings] + + # Certain fields should be provided within 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_attribution_settings(self, + request: Optional[Union[analytics_admin.UpdateAttributionSettingsRequest, dict]] = None, + *, + attribution_settings: Optional[resources.AttributionSettings] = 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]] = (), + ) -> resources.AttributionSettings: + r"""Updates attribution settings on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAttributionSettingsRequest, dict]]): + The request object. Request message for + UpdateAttributionSettings RPC + attribution_settings (:class:`google.analytics.admin_v1alpha.types.AttributionSettings`): + Required. The attribution settings to update. The + ``name`` field is used to identify the settings to be + updated. + + This corresponds to the ``attribution_settings`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attribution_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAttributionSettingsRequest): + request = analytics_admin.UpdateAttributionSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attribution_settings is not None: + request.attribution_settings = attribution_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_attribution_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attribution_settings.name", request.attribution_settings.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 run_access_report(self, + request: Optional[Union[analytics_admin.RunAccessReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.RunAccessReportResponse: + r"""Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. + + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.RunAccessReportRequest, dict]]): + The request object. The request for a Data Access Record + Report. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.RunAccessReportResponse: + The customized Data Access Record + Report response. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.RunAccessReportRequest): + request = analytics_admin.RunAccessReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.run_access_report] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity", request.entity), + )), + ) + + # 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_access_binding(self, + request: Optional[Union[analytics_admin.CreateAccessBindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + access_binding: Optional[resources.AccessBinding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AccessBinding: + r"""Creates an access binding on an account or property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateAccessBindingRequest, dict]]): + The request object. Request message for + CreateAccessBinding RPC. + parent (:class:`str`): + Required. Formats: + + - accounts/{account} + - properties/{property} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + access_binding (:class:`google.analytics.admin_v1alpha.types.AccessBinding`): + Required. The access binding to + create. + + This corresponds to the ``access_binding`` 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.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, access_binding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateAccessBindingRequest): + request = analytics_admin.CreateAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if access_binding is not None: + request.access_binding = access_binding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_access_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_access_binding(self, + request: Optional[Union[analytics_admin.GetAccessBindingRequest, 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]] = (), + ) -> resources.AccessBinding: + r"""Gets information about an access binding. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetAccessBindingRequest, dict]]): + The request object. Request message for GetAccessBinding + RPC. + name (:class:`str`): + Required. The name of the access + binding to retrieve. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} + + 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.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAccessBindingRequest): + request = analytics_admin.GetAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_access_binding] + + # Certain fields should be provided within 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_access_binding(self, + request: Optional[Union[analytics_admin.UpdateAccessBindingRequest, dict]] = None, + *, + access_binding: Optional[resources.AccessBinding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AccessBinding: + r"""Updates an access binding on an account or property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateAccessBindingRequest, dict]]): + The request object. Request message for + UpdateAccessBinding RPC. + access_binding (:class:`google.analytics.admin_v1alpha.types.AccessBinding`): + Required. The access binding to + update. + + This corresponds to the ``access_binding`` 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.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([access_binding]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAccessBindingRequest): + request = analytics_admin.UpdateAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if access_binding is not None: + request.access_binding = access_binding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_access_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("access_binding.name", request.access_binding.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_access_binding(self, + request: Optional[Union[analytics_admin.DeleteAccessBindingRequest, 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 an access binding on an account or property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteAccessBindingRequest, dict]]): + The request object. Request message for + DeleteAccessBinding RPC. + name (:class:`str`): + Required. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAccessBindingRequest): + request = analytics_admin.DeleteAccessBindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_access_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_access_bindings(self, + request: Optional[Union[analytics_admin.ListAccessBindingsRequest, 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.ListAccessBindingsAsyncPager: + r"""Lists all access bindings on an account or property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListAccessBindingsRequest, dict]]): + The request object. Request message for + ListAccessBindings RPC. + parent (:class:`str`): + Required. Formats: + + - accounts/{account} + - properties/{property} + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccessBindingsAsyncPager: + Response message for + ListAccessBindings RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccessBindingsRequest): + request = analytics_admin.ListAccessBindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_access_bindings] + + # Certain 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.ListAccessBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_create_access_bindings(self, + request: Optional[Union[analytics_admin.BatchCreateAccessBindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.BatchCreateAccessBindingsResponse: + r"""Creates information about multiple access bindings to + an account or property. + + This method is transactional. If any AccessBinding + cannot be created, none of the AccessBindings will be + created. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsRequest, dict]]): + The request object. Request message for + BatchCreateAccessBindings RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsResponse: + Response message for + BatchCreateAccessBindings RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchCreateAccessBindingsRequest): + request = analytics_admin.BatchCreateAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_create_access_bindings] + + # Certain 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 batch_get_access_bindings(self, + request: Optional[Union[analytics_admin.BatchGetAccessBindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.BatchGetAccessBindingsResponse: + r"""Gets information about multiple access bindings to an + account or property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.BatchGetAccessBindingsRequest, dict]]): + The request object. Request message for + BatchGetAccessBindings RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BatchGetAccessBindingsResponse: + Response message for + BatchGetAccessBindings RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchGetAccessBindingsRequest): + request = analytics_admin.BatchGetAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_get_access_bindings] + + # Certain 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 batch_update_access_bindings(self, + request: Optional[Union[analytics_admin.BatchUpdateAccessBindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.BatchUpdateAccessBindingsResponse: + r"""Updates information about multiple access bindings to + an account or property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsRequest, dict]]): + The request object. Request message for + BatchUpdateAccessBindings RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsResponse: + Response message for + BatchUpdateAccessBindings RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchUpdateAccessBindingsRequest): + request = analytics_admin.BatchUpdateAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_update_access_bindings] + + # Certain 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 batch_delete_access_bindings(self, + request: Optional[Union[analytics_admin.BatchDeleteAccessBindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes information about multiple users' links to an + account or property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.BatchDeleteAccessBindingsRequest, dict]]): + The request object. Request message for + BatchDeleteAccessBindings RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchDeleteAccessBindingsRequest): + request = analytics_admin.BatchDeleteAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.batch_delete_access_bindings] + + # Certain 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_expanded_data_set(self, + request: Optional[Union[analytics_admin.GetExpandedDataSetRequest, 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]] = (), + ) -> expanded_data_set.ExpandedDataSet: + r"""Lookup for a single ExpandedDataSet. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetExpandedDataSetRequest, dict]]): + The request object. Request message for + GetExpandedDataSet RPC. + name (:class:`str`): + Required. The name of the + ExpandedDataSet to get. Example format: + properties/1234/expandedDataSets/5678 + + 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.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetExpandedDataSetRequest): + request = analytics_admin.GetExpandedDataSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_expanded_data_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_expanded_data_sets(self, + request: Optional[Union[analytics_admin.ListExpandedDataSetsRequest, 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.ListExpandedDataSetsAsyncPager: + r"""Lists ExpandedDataSets on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListExpandedDataSetsRequest, dict]]): + The request object. Request message for + ListExpandedDataSets RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListExpandedDataSetsAsyncPager: + Response message for + ListExpandedDataSets RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListExpandedDataSetsRequest): + request = analytics_admin.ListExpandedDataSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_expanded_data_sets] + + # Certain 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.ListExpandedDataSetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_expanded_data_set(self, + request: Optional[Union[analytics_admin.CreateExpandedDataSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Creates a ExpandedDataSet. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateExpandedDataSetRequest, dict]]): + The request object. Request message for + CreateExpandedDataSet RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + expanded_data_set (:class:`google.analytics.admin_v1alpha.types.ExpandedDataSet`): + Required. The ExpandedDataSet to + create. + + This corresponds to the ``expanded_data_set`` 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.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, expanded_data_set]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateExpandedDataSetRequest): + request = analytics_admin.CreateExpandedDataSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if expanded_data_set is not None: + request.expanded_data_set = expanded_data_set + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_expanded_data_set] + + # Certain 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_expanded_data_set(self, + request: Optional[Union[analytics_admin.UpdateExpandedDataSetRequest, dict]] = None, + *, + expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = 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]] = (), + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Updates a ExpandedDataSet on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateExpandedDataSetRequest, dict]]): + The request object. Request message for + UpdateExpandedDataSet RPC. + expanded_data_set (:class:`google.analytics.admin_v1alpha.types.ExpandedDataSet`): + Required. The ExpandedDataSet to update. The resource's + ``name`` field is used to identify the ExpandedDataSet + to be updated. + + This corresponds to the ``expanded_data_set`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([expanded_data_set, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateExpandedDataSetRequest): + request = analytics_admin.UpdateExpandedDataSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if expanded_data_set is not None: + request.expanded_data_set = expanded_data_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_expanded_data_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("expanded_data_set.name", request.expanded_data_set.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_expanded_data_set(self, + request: Optional[Union[analytics_admin.DeleteExpandedDataSetRequest, 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 ExpandedDataSet on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteExpandedDataSetRequest, dict]]): + The request object. Request message for + DeleteExpandedDataSet RPC. + name (:class:`str`): + Required. Example format: + properties/1234/expandedDataSets/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteExpandedDataSetRequest): + request = analytics_admin.DeleteExpandedDataSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_expanded_data_set] + + # Certain fields should be provided within 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_channel_group(self, + request: Optional[Union[analytics_admin.GetChannelGroupRequest, 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]] = (), + ) -> channel_group.ChannelGroup: + r"""Lookup for a single ChannelGroup. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetChannelGroupRequest, dict]]): + The request object. Request message for GetChannelGroup + RPC. + name (:class:`str`): + Required. The ChannelGroup to get. + Example format: + properties/1234/channelGroups/5678 + + 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.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetChannelGroupRequest): + request = analytics_admin.GetChannelGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_channel_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_channel_groups(self, + request: Optional[Union[analytics_admin.ListChannelGroupsRequest, 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.ListChannelGroupsAsyncPager: + r"""Lists ChannelGroups on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListChannelGroupsRequest, dict]]): + The request object. Request message for ListChannelGroups + RPC. + parent (:class:`str`): + Required. The property for which to + list ChannelGroups. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListChannelGroupsAsyncPager: + Response message for + ListChannelGroups RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListChannelGroupsRequest): + request = analytics_admin.ListChannelGroupsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_channel_groups] + + # Certain 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.ListChannelGroupsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_channel_group(self, + request: Optional[Union[analytics_admin.CreateChannelGroupRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel_group: Optional[gaa_channel_group.ChannelGroup] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gaa_channel_group.ChannelGroup: + r"""Creates a ChannelGroup. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateChannelGroupRequest, dict]]): + The request object. Request message for + CreateChannelGroup RPC. + parent (:class:`str`): + Required. The property for which to + create a ChannelGroup. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_group (:class:`google.analytics.admin_v1alpha.types.ChannelGroup`): + Required. The ChannelGroup to create. + This corresponds to the ``channel_group`` 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.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel_group]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateChannelGroupRequest): + request = analytics_admin.CreateChannelGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel_group is not None: + request.channel_group = channel_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_channel_group] + + # Certain 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_channel_group(self, + request: Optional[Union[analytics_admin.UpdateChannelGroupRequest, dict]] = None, + *, + channel_group: Optional[gaa_channel_group.ChannelGroup] = 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]] = (), + ) -> gaa_channel_group.ChannelGroup: + r"""Updates a ChannelGroup. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateChannelGroupRequest, dict]]): + The request object. Request message for + UpdateChannelGroup RPC. + channel_group (:class:`google.analytics.admin_v1alpha.types.ChannelGroup`): + Required. The ChannelGroup to update. The resource's + ``name`` field is used to identify the ChannelGroup to + be updated. + + This corresponds to the ``channel_group`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([channel_group, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateChannelGroupRequest): + request = analytics_admin.UpdateChannelGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if channel_group is not None: + request.channel_group = channel_group + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_channel_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("channel_group.name", request.channel_group.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_channel_group(self, + request: Optional[Union[analytics_admin.DeleteChannelGroupRequest, 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 ChannelGroup on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteChannelGroupRequest, dict]]): + The request object. Request message for + DeleteChannelGroup RPC. + name (:class:`str`): + Required. The ChannelGroup to delete. + Example format: + properties/1234/channelGroups/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteChannelGroupRequest): + request = analytics_admin.DeleteChannelGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_channel_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def set_automated_ga4_configuration_opt_out(self, + request: Optional[Union[analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse: + r"""Sets the opt out status for the automated GA4 setup + process for a UA property. + Note: this has no effect on GA4 property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutRequest, dict]]): + The request object. Request for setting the opt out + status for the automated GA4 setup + process. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutResponse: + Response message for setting the opt + out status for the automated GA4 setup + process. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest): + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.set_automated_ga4_configuration_opt_out] + + # 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 fetch_automated_ga4_configuration_opt_out(self, + request: Optional[Union[analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse: + r"""Fetches the opt out status for the automated GA4 + setup process for a UA property. + Note: this has no effect on GA4 property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutRequest, dict]]): + The request object. Request for fetching the opt out + status for the automated GA4 setup + process. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutResponse: + Response message for fetching the opt + out status for the automated GA4 setup + process. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest): + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_automated_ga4_configuration_opt_out] + + # 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_big_query_link(self, + request: Optional[Union[analytics_admin.CreateBigQueryLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + bigquery_link: Optional[resources.BigQueryLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.BigQueryLink: + r"""Creates a BigQueryLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateBigQueryLinkRequest, dict]]): + The request object. Request message for + CreateBigQueryLink RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + bigquery_link (:class:`google.analytics.admin_v1alpha.types.BigQueryLink`): + Required. The BigQueryLink to create. + This corresponds to the ``bigquery_link`` 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.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, bigquery_link]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateBigQueryLinkRequest): + request = analytics_admin.CreateBigQueryLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if bigquery_link is not None: + request.bigquery_link = bigquery_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_big_query_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_big_query_link(self, + request: Optional[Union[analytics_admin.GetBigQueryLinkRequest, 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]] = (), + ) -> resources.BigQueryLink: + r"""Lookup for a single BigQuery Link. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetBigQueryLinkRequest, dict]]): + The request object. Request message for GetBigQueryLink + RPC. + name (:class:`str`): + Required. The name of the BigQuery link to lookup. + Format: + properties/{property_id}/bigQueryLinks/{bigquery_link_id} + Example: properties/123/bigQueryLinks/456 + + 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.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetBigQueryLinkRequest): + request = analytics_admin.GetBigQueryLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_big_query_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_big_query_links(self, + request: Optional[Union[analytics_admin.ListBigQueryLinksRequest, 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.ListBigQueryLinksAsyncPager: + r"""Lists BigQuery Links on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListBigQueryLinksRequest, dict]]): + The request object. Request message for ListBigQueryLinks + RPC. + parent (:class:`str`): + Required. The name of the property to list BigQuery + links under. Format: properties/{property_id} Example: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListBigQueryLinksAsyncPager: + Response message for + ListBigQueryLinks RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListBigQueryLinksRequest): + request = analytics_admin.ListBigQueryLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_big_query_links] + + # Certain 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.ListBigQueryLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_big_query_link(self, + request: Optional[Union[analytics_admin.DeleteBigQueryLinkRequest, 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 BigQueryLink on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteBigQueryLinkRequest, dict]]): + The request object. Request message for + DeleteBigQueryLink RPC. + name (:class:`str`): + Required. The BigQueryLink to delete. + Example format: + properties/1234/bigQueryLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteBigQueryLinkRequest): + request = analytics_admin.DeleteBigQueryLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_big_query_link] + + # Certain fields should be provided within 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 update_big_query_link(self, + request: Optional[Union[analytics_admin.UpdateBigQueryLinkRequest, dict]] = None, + *, + bigquery_link: Optional[resources.BigQueryLink] = 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]] = (), + ) -> resources.BigQueryLink: + r"""Updates a BigQueryLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateBigQueryLinkRequest, dict]]): + The request object. Request message for + UpdateBigQueryLink RPC. + bigquery_link (:class:`google.analytics.admin_v1alpha.types.BigQueryLink`): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``bigquery_link`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([bigquery_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateBigQueryLinkRequest): + request = analytics_admin.UpdateBigQueryLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if bigquery_link is not None: + request.bigquery_link = bigquery_link + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_big_query_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("bigquery_link.name", request.bigquery_link.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_enhanced_measurement_settings(self, + request: Optional[Union[analytics_admin.GetEnhancedMeasurementSettingsRequest, 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]] = (), + ) -> resources.EnhancedMeasurementSettings: + r"""Returns the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetEnhancedMeasurementSettingsRequest, dict]]): + The request object. Request message for + GetEnhancedMeasurementSettings RPC. + name (:class:`str`): + Required. The name of the settings to lookup. Format: + properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings + Example: + "properties/1000/dataStreams/2000/enhancedMeasurementSettings" + + 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.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetEnhancedMeasurementSettingsRequest): + request = analytics_admin.GetEnhancedMeasurementSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_enhanced_measurement_settings] + + # Certain fields should be provided within 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_enhanced_measurement_settings(self, + request: Optional[Union[analytics_admin.UpdateEnhancedMeasurementSettingsRequest, dict]] = None, + *, + enhanced_measurement_settings: Optional[resources.EnhancedMeasurementSettings] = 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]] = (), + ) -> resources.EnhancedMeasurementSettings: + r"""Updates the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateEnhancedMeasurementSettingsRequest, dict]]): + The request object. Request message for + UpdateEnhancedMeasurementSettings RPC. + enhanced_measurement_settings (:class:`google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings`): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``enhanced_measurement_settings`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([enhanced_measurement_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateEnhancedMeasurementSettingsRequest): + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if enhanced_measurement_settings is not None: + request.enhanced_measurement_settings = enhanced_measurement_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_enhanced_measurement_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("enhanced_measurement_settings.name", request.enhanced_measurement_settings.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_connected_site_tag(self, + request: Optional[Union[analytics_admin.CreateConnectedSiteTagRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.CreateConnectedSiteTagResponse: + r"""Creates a connected site tag for a Universal + Analytics property. You can create a maximum of 20 + connected site tags per property. Note: This API cannot + be used on GA4 properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateConnectedSiteTagRequest, dict]]): + The request object. Request message for + CreateConnectedSiteTag RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CreateConnectedSiteTagResponse: + Response message for + CreateConnectedSiteTag RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateConnectedSiteTagRequest): + request = analytics_admin.CreateConnectedSiteTagRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_connected_site_tag] + + # 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_connected_site_tag(self, + request: Optional[Union[analytics_admin.DeleteConnectedSiteTagRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a connected site tag for a Universal + Analytics property. Note: this has no effect on GA4 + properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteConnectedSiteTagRequest, dict]]): + The request object. Request message for + DeleteConnectedSiteTag RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteConnectedSiteTagRequest): + request = analytics_admin.DeleteConnectedSiteTagRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_connected_site_tag] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_connected_site_tags(self, + request: Optional[Union[analytics_admin.ListConnectedSiteTagsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ListConnectedSiteTagsResponse: + r"""Lists the connected site tags for a Universal + Analytics property. A maximum of 20 connected site tags + will be returned. Note: this has no effect on GA4 + property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListConnectedSiteTagsRequest, dict]]): + The request object. Request message for + ListConnectedSiteTags RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ListConnectedSiteTagsResponse: + Response message for + ListConnectedSiteTags RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListConnectedSiteTagsRequest): + request = analytics_admin.ListConnectedSiteTagsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_connected_site_tags] + + # 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 fetch_connected_ga4_property(self, + request: Optional[Union[analytics_admin.FetchConnectedGa4PropertyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.FetchConnectedGa4PropertyResponse: + r"""Given a specified UA property, looks up the GA4 + property connected to it. Note: this cannot be used with + GA4 properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyRequest, dict]]): + The request object. Request for looking up GA4 property + connected to a UA property. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyResponse: + Response for looking up GA4 property + connected to a UA property. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.FetchConnectedGa4PropertyRequest): + request = analytics_admin.FetchConnectedGa4PropertyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.fetch_connected_ga4_property] + + # 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_ad_sense_link(self, + request: Optional[Union[analytics_admin.GetAdSenseLinkRequest, 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]] = (), + ) -> resources.AdSenseLink: + r"""Looks up a single AdSenseLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetAdSenseLinkRequest, dict]]): + The request object. Request message to be passed to + GetAdSenseLink method. + name (:class:`str`): + Required. Unique identifier for the + AdSense Link requested. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: + properties/1234/adSenseLinks/5678 + + 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.analytics.admin_v1alpha.types.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAdSenseLinkRequest): + request = analytics_admin.GetAdSenseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_ad_sense_link] + + # Certain fields should be provided within 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_ad_sense_link(self, + request: Optional[Union[analytics_admin.CreateAdSenseLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + adsense_link: Optional[resources.AdSenseLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AdSenseLink: + r"""Creates an AdSenseLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateAdSenseLinkRequest, dict]]): + The request object. Request message to be passed to + CreateAdSenseLink method. + parent (:class:`str`): + Required. The property for which to + create an AdSense Link. Format: + properties/{propertyId} Example: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + adsense_link (:class:`google.analytics.admin_v1alpha.types.AdSenseLink`): + Required. The AdSense Link to create + This corresponds to the ``adsense_link`` 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.analytics.admin_v1alpha.types.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, adsense_link]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateAdSenseLinkRequest): + request = analytics_admin.CreateAdSenseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if adsense_link is not None: + request.adsense_link = adsense_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_ad_sense_link] + + # Certain 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 delete_ad_sense_link(self, + request: Optional[Union[analytics_admin.DeleteAdSenseLinkRequest, 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 an AdSenseLink. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteAdSenseLinkRequest, dict]]): + The request object. Request message to be passed to + DeleteAdSenseLink method. + name (:class:`str`): + Required. Unique identifier for the + AdSense Link to be deleted. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: + properties/1234/adSenseLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAdSenseLinkRequest): + request = analytics_admin.DeleteAdSenseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_ad_sense_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_ad_sense_links(self, + request: Optional[Union[analytics_admin.ListAdSenseLinksRequest, 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.ListAdSenseLinksAsyncPager: + r"""Lists AdSenseLinks on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListAdSenseLinksRequest, dict]]): + The request object. Request message to be passed to + ListAdSenseLinks method. + parent (:class:`str`): + Required. Resource name of the parent + property. Format: + properties/{propertyId} + Example: properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAdSenseLinksAsyncPager: + Response message for ListAdSenseLinks + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAdSenseLinksRequest): + request = analytics_admin.ListAdSenseLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_ad_sense_links] + + # Certain 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.ListAdSenseLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_event_create_rule(self, + request: Optional[Union[analytics_admin.GetEventCreateRuleRequest, 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]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Lookup for a single EventCreateRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetEventCreateRuleRequest, dict]]): + The request object. Request message for + GetEventCreateRule RPC. + name (:class:`str`): + Required. The name of the + EventCreateRule to get. Example format: + properties/123/dataStreams/456/eventCreateRules/789 + + 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.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetEventCreateRuleRequest): + request = analytics_admin.GetEventCreateRuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_event_create_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_event_create_rules(self, + request: Optional[Union[analytics_admin.ListEventCreateRulesRequest, 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.ListEventCreateRulesAsyncPager: + r"""Lists EventCreateRules on a web data stream. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListEventCreateRulesRequest, dict]]): + The request object. Request message for + ListEventCreateRules RPC. + parent (:class:`str`): + Required. Example format: + properties/123/dataStreams/456 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventCreateRulesAsyncPager: + Response message for + ListEventCreateRules RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListEventCreateRulesRequest): + request = analytics_admin.ListEventCreateRulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_event_create_rules] + + # Certain 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.ListEventCreateRulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_event_create_rule(self, + request: Optional[Union[analytics_admin.CreateEventCreateRuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Creates an EventCreateRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateEventCreateRuleRequest, dict]]): + The request object. Request message for + CreateEventCreateRule RPC. + parent (:class:`str`): + Required. Example format: + properties/123/dataStreams/456 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_create_rule (:class:`google.analytics.admin_v1alpha.types.EventCreateRule`): + Required. The EventCreateRule to + create. + + This corresponds to the ``event_create_rule`` 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.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event_create_rule]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateEventCreateRuleRequest): + request = analytics_admin.CreateEventCreateRuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event_create_rule is not None: + request.event_create_rule = event_create_rule + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_event_create_rule] + + # Certain 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_event_create_rule(self, + request: Optional[Union[analytics_admin.UpdateEventCreateRuleRequest, dict]] = None, + *, + event_create_rule: Optional[event_create_and_edit.EventCreateRule] = 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]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Updates an EventCreateRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateEventCreateRuleRequest, dict]]): + The request object. Request message for + UpdateEventCreateRule RPC. + event_create_rule (:class:`google.analytics.admin_v1alpha.types.EventCreateRule`): + Required. The EventCreateRule to update. The resource's + ``name`` field is used to identify the EventCreateRule + to be updated. + + This corresponds to the ``event_create_rule`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event_create_rule, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateEventCreateRuleRequest): + request = analytics_admin.UpdateEventCreateRuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event_create_rule is not None: + request.event_create_rule = event_create_rule + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_event_create_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event_create_rule.name", request.event_create_rule.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_event_create_rule(self, + request: Optional[Union[analytics_admin.DeleteEventCreateRuleRequest, 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 an EventCreateRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteEventCreateRuleRequest, dict]]): + The request object. Request message for + DeleteEventCreateRule RPC. + name (:class:`str`): + Required. Example format: + + properties/123/dataStreams/456/eventCreateRules/789 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteEventCreateRuleRequest): + request = analytics_admin.DeleteEventCreateRuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_event_create_rule] + + # Certain fields should be provided within 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_event_edit_rule(self, + request: Optional[Union[analytics_admin.GetEventEditRuleRequest, 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]] = (), + ) -> event_create_and_edit.EventEditRule: + r"""Lookup for a single EventEditRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetEventEditRuleRequest, dict]]): + The request object. Request message for GetEventEditRule + RPC. + name (:class:`str`): + Required. The name of the + EventEditRule to get. Example format: + properties/123/dataStreams/456/eventEditRules/789 + + 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.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetEventEditRuleRequest): + request = analytics_admin.GetEventEditRuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_event_edit_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_event_edit_rules(self, + request: Optional[Union[analytics_admin.ListEventEditRulesRequest, 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.ListEventEditRulesAsyncPager: + r"""Lists EventEditRules on a web data stream. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListEventEditRulesRequest, dict]]): + The request object. Request message for + ListEventEditRules RPC. + parent (:class:`str`): + Required. Example format: + properties/123/dataStreams/456 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventEditRulesAsyncPager: + Response message for + ListEventEditRules RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListEventEditRulesRequest): + request = analytics_admin.ListEventEditRulesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_event_edit_rules] + + # Certain 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.ListEventEditRulesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_event_edit_rule(self, + request: Optional[Union[analytics_admin.CreateEventEditRuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + event_edit_rule: Optional[event_create_and_edit.EventEditRule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventEditRule: + r"""Creates an EventEditRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateEventEditRuleRequest, dict]]): + The request object. Request message for + CreateEventEditRule RPC. + parent (:class:`str`): + Required. Example format: + properties/123/dataStreams/456 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_edit_rule (:class:`google.analytics.admin_v1alpha.types.EventEditRule`): + Required. The EventEditRule to + create. + + This corresponds to the ``event_edit_rule`` 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.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event_edit_rule]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateEventEditRuleRequest): + request = analytics_admin.CreateEventEditRuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event_edit_rule is not None: + request.event_edit_rule = event_edit_rule + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_event_edit_rule] + + # Certain 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_event_edit_rule(self, + request: Optional[Union[analytics_admin.UpdateEventEditRuleRequest, dict]] = None, + *, + event_edit_rule: Optional[event_create_and_edit.EventEditRule] = 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]] = (), + ) -> event_create_and_edit.EventEditRule: + r"""Updates an EventEditRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateEventEditRuleRequest, dict]]): + The request object. Request message for + UpdateEventEditRule RPC. + event_edit_rule (:class:`google.analytics.admin_v1alpha.types.EventEditRule`): + Required. The EventEditRule to update. The resource's + ``name`` field is used to identify the EventEditRule to + be updated. + + This corresponds to the ``event_edit_rule`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event_edit_rule, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateEventEditRuleRequest): + request = analytics_admin.UpdateEventEditRuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event_edit_rule is not None: + request.event_edit_rule = event_edit_rule + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_event_edit_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event_edit_rule.name", request.event_edit_rule.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_event_edit_rule(self, + request: Optional[Union[analytics_admin.DeleteEventEditRuleRequest, 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 an EventEditRule. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteEventEditRuleRequest, dict]]): + The request object. Request message for + DeleteEventEditRule RPC. + name (:class:`str`): + Required. Example format: + properties/123/dataStreams/456/eventEditRules/789 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteEventEditRuleRequest): + request = analytics_admin.DeleteEventEditRuleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_event_edit_rule] + + # Certain fields should be provided within 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 reorder_event_edit_rules(self, + request: Optional[Union[analytics_admin.ReorderEventEditRulesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Changes the processing order of event edit rules on + the specified stream. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ReorderEventEditRulesRequest, dict]]): + The request object. Request message for + ReorderEventEditRules RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ReorderEventEditRulesRequest): + request = analytics_admin.ReorderEventEditRulesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.reorder_event_edit_rules] + + # Certain 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_data_redaction_settings(self, + request: Optional[Union[analytics_admin.UpdateDataRedactionSettingsRequest, dict]] = None, + *, + data_redaction_settings: Optional[resources.DataRedactionSettings] = 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]] = (), + ) -> resources.DataRedactionSettings: + r"""Updates a DataRedactionSettings on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateDataRedactionSettingsRequest, dict]]): + The request object. Request message for + UpdateDataRedactionSettings RPC. + data_redaction_settings (:class:`google.analytics.admin_v1alpha.types.DataRedactionSettings`): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``data_redaction_settings`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DataRedactionSettings: + Settings for client-side data + redaction. Singleton resource under a + Web Stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_redaction_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataRedactionSettingsRequest): + request = analytics_admin.UpdateDataRedactionSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_redaction_settings is not None: + request.data_redaction_settings = data_redaction_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_data_redaction_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_redaction_settings.name", request.data_redaction_settings.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_data_redaction_settings(self, + request: Optional[Union[analytics_admin.GetDataRedactionSettingsRequest, 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]] = (), + ) -> resources.DataRedactionSettings: + r"""Lookup for a single DataRedactionSettings. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetDataRedactionSettingsRequest, dict]]): + The request object. Request message for + GetDataRedactionSettings RPC. + name (:class:`str`): + Required. The name of the settings to lookup. Format: + properties/{property}/dataStreams/{data_stream}/dataRedactionSettings + Example: + "properties/1000/dataStreams/2000/dataRedactionSettings" + + 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.analytics.admin_v1alpha.types.DataRedactionSettings: + Settings for client-side data + redaction. Singleton resource under a + Web Stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataRedactionSettingsRequest): + request = analytics_admin.GetDataRedactionSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_data_redaction_settings] + + # Certain fields should be provided within 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_calculated_metric(self, + request: Optional[Union[analytics_admin.GetCalculatedMetricRequest, 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]] = (), + ) -> resources.CalculatedMetric: + r"""Lookup for a single CalculatedMetric. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetCalculatedMetricRequest, dict]]): + The request object. Request message for + GetCalculatedMetric RPC. + name (:class:`str`): + Required. The name of the CalculatedMetric to get. + Format: + properties/{property_id}/calculatedMetrics/{calculated_metric_id} + Example: properties/1234/calculatedMetrics/Metric01 + + 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.analytics.admin_v1alpha.types.CalculatedMetric: + A definition for a calculated metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCalculatedMetricRequest): + request = analytics_admin.GetCalculatedMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_calculated_metric] + + # Certain fields should be provided within 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_calculated_metric(self, + request: Optional[Union[analytics_admin.CreateCalculatedMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + calculated_metric: Optional[resources.CalculatedMetric] = None, + calculated_metric_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CalculatedMetric: + r"""Creates a CalculatedMetric. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateCalculatedMetricRequest, dict]]): + The request object. Request message for + CreateCalculatedMetric RPC. + parent (:class:`str`): + Required. Format: properties/{property_id} Example: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + calculated_metric (:class:`google.analytics.admin_v1alpha.types.CalculatedMetric`): + Required. The CalculatedMetric to + create. + + This corresponds to the ``calculated_metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + calculated_metric_id (:class:`str`): + Required. The ID to use for the calculated metric which + will become the final component of the calculated + metric's resource name. + + This value should be 1-80 characters and valid + characters are /[a-zA-Z0-9_]/, no spaces allowed. + calculated_metric_id must be unique between all + calculated metrics under a property. The + calculated_metric_id is used when referencing this + calculated metric from external APIs, for example, + "calcMetric:{calculated_metric_id}". + + This corresponds to the ``calculated_metric_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.analytics.admin_v1alpha.types.CalculatedMetric: + A definition for a calculated metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, calculated_metric, calculated_metric_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCalculatedMetricRequest): + request = analytics_admin.CreateCalculatedMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if calculated_metric is not None: + request.calculated_metric = calculated_metric + if calculated_metric_id is not None: + request.calculated_metric_id = calculated_metric_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_calculated_metric] + + # Certain 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_calculated_metrics(self, + request: Optional[Union[analytics_admin.ListCalculatedMetricsRequest, 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.ListCalculatedMetricsAsyncPager: + r"""Lists CalculatedMetrics on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListCalculatedMetricsRequest, dict]]): + The request object. Request message for + ListCalculatedMetrics RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCalculatedMetricsAsyncPager: + Response message for + ListCalculatedMetrics RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCalculatedMetricsRequest): + request = analytics_admin.ListCalculatedMetricsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_calculated_metrics] + + # Certain 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.ListCalculatedMetricsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_calculated_metric(self, + request: Optional[Union[analytics_admin.UpdateCalculatedMetricRequest, dict]] = None, + *, + calculated_metric: Optional[resources.CalculatedMetric] = 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]] = (), + ) -> resources.CalculatedMetric: + r"""Updates a CalculatedMetric on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateCalculatedMetricRequest, dict]]): + The request object. Request message for + UpdateCalculatedMetric RPC. + calculated_metric (:class:`google.analytics.admin_v1alpha.types.CalculatedMetric`): + Required. The CalculatedMetric to + update + + This corresponds to the ``calculated_metric`` 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 list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CalculatedMetric: + A definition for a calculated metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([calculated_metric, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCalculatedMetricRequest): + request = analytics_admin.UpdateCalculatedMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if calculated_metric is not None: + request.calculated_metric = calculated_metric + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_calculated_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("calculated_metric.name", request.calculated_metric.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_calculated_metric(self, + request: Optional[Union[analytics_admin.DeleteCalculatedMetricRequest, 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 CalculatedMetric on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteCalculatedMetricRequest, dict]]): + The request object. Request message for + DeleteCalculatedMetric RPC. + name (:class:`str`): + Required. The name of the CalculatedMetric to delete. + Format: + properties/{property_id}/calculatedMetrics/{calculated_metric_id} + Example: properties/1234/calculatedMetrics/Metric01 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteCalculatedMetricRequest): + request = analytics_admin.DeleteCalculatedMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_calculated_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_rollup_property(self, + request: Optional[Union[analytics_admin.CreateRollupPropertyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.CreateRollupPropertyResponse: + r"""Create a roll-up property and all roll-up property + source links. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateRollupPropertyRequest, dict]]): + The request object. Request message for + CreateRollupProperty RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CreateRollupPropertyResponse: + Response message for + CreateRollupProperty RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateRollupPropertyRequest): + request = analytics_admin.CreateRollupPropertyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_rollup_property] + + # 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_rollup_property_source_link(self, + request: Optional[Union[analytics_admin.GetRollupPropertySourceLinkRequest, 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]] = (), + ) -> resources.RollupPropertySourceLink: + r"""Lookup for a single roll-up property source Link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetRollupPropertySourceLinkRequest, dict]]): + The request object. Request message for + GetRollupPropertySourceLink RPC. + name (:class:`str`): + Required. The name of the roll-up property source link + to lookup. Format: + properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} + Example: properties/123/rollupPropertySourceLinks/456 + + 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.analytics.admin_v1alpha.types.RollupPropertySourceLink: + A link that references a source + property under the parent rollup + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetRollupPropertySourceLinkRequest): + request = analytics_admin.GetRollupPropertySourceLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_rollup_property_source_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_rollup_property_source_links(self, + request: Optional[Union[analytics_admin.ListRollupPropertySourceLinksRequest, 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.ListRollupPropertySourceLinksAsyncPager: + r"""Lists roll-up property source Links on a property. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksRequest, dict]]): + The request object. Request message for + ListRollupPropertySourceLinks RPC. + parent (:class:`str`): + Required. The name of the roll-up property to list + roll-up property source links under. Format: + properties/{property_id} Example: properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListRollupPropertySourceLinksAsyncPager: + Response message for + ListRollupPropertySourceLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListRollupPropertySourceLinksRequest): + request = analytics_admin.ListRollupPropertySourceLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_rollup_property_source_links] + + # Certain 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.ListRollupPropertySourceLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_rollup_property_source_link(self, + request: Optional[Union[analytics_admin.CreateRollupPropertySourceLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + rollup_property_source_link: Optional[resources.RollupPropertySourceLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.RollupPropertySourceLink: + r"""Creates a roll-up property source link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateRollupPropertySourceLinkRequest, dict]]): + The request object. Request message for + CreateRollupPropertySourceLink RPC. + parent (:class:`str`): + Required. Format: properties/{property_id} Example: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollup_property_source_link (:class:`google.analytics.admin_v1alpha.types.RollupPropertySourceLink`): + Required. The roll-up property source + link to create. + + This corresponds to the ``rollup_property_source_link`` 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.analytics.admin_v1alpha.types.RollupPropertySourceLink: + A link that references a source + property under the parent rollup + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, rollup_property_source_link]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateRollupPropertySourceLinkRequest): + request = analytics_admin.CreateRollupPropertySourceLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if rollup_property_source_link is not None: + request.rollup_property_source_link = rollup_property_source_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_rollup_property_source_link] + + # Certain 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 delete_rollup_property_source_link(self, + request: Optional[Union[analytics_admin.DeleteRollupPropertySourceLinkRequest, 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 roll-up property source link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteRollupPropertySourceLinkRequest, dict]]): + The request object. Request message for + DeleteRollupPropertySourceLink RPC. + name (:class:`str`): + Required. Format: + properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} + Example: properties/1234/rollupPropertySourceLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteRollupPropertySourceLinkRequest): + request = analytics_admin.DeleteRollupPropertySourceLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_rollup_property_source_link] + + # Certain fields should be provided within 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 provision_subproperty(self, + request: Optional[Union[analytics_admin.ProvisionSubpropertyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ProvisionSubpropertyResponse: + r"""Create a subproperty and a subproperty event filter + that applies to the created subproperty. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ProvisionSubpropertyRequest, dict]]): + The request object. Request message for CreateSubproperty + RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ProvisionSubpropertyResponse: + Response message for + ProvisionSubproperty RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ProvisionSubpropertyRequest): + request = analytics_admin.ProvisionSubpropertyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.provision_subproperty] + + # 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_subproperty_event_filter(self, + request: Optional[Union[analytics_admin.CreateSubpropertyEventFilterRequest, dict]] = None, + *, + parent: Optional[str] = None, + subproperty_event_filter: Optional[gaa_subproperty_event_filter.SubpropertyEventFilter] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gaa_subproperty_event_filter.SubpropertyEventFilter: + r"""Creates a subproperty Event Filter. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.CreateSubpropertyEventFilterRequest, dict]]): + The request object. Request message for + CreateSubpropertyEventFilter RPC. + parent (:class:`str`): + Required. The ordinary property for which to create a + subproperty event filter. Format: properties/property_id + Example: properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subproperty_event_filter (:class:`google.analytics.admin_v1alpha.types.SubpropertyEventFilter`): + Required. The subproperty event + filter to create. + + This corresponds to the ``subproperty_event_filter`` 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.analytics.admin_v1alpha.types.SubpropertyEventFilter: + A resource message representing a GA4 + Subproperty event filter. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, subproperty_event_filter]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateSubpropertyEventFilterRequest): + request = analytics_admin.CreateSubpropertyEventFilterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if subproperty_event_filter is not None: + request.subproperty_event_filter = subproperty_event_filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_subproperty_event_filter] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_subproperty_event_filter(self, + request: Optional[Union[analytics_admin.GetSubpropertyEventFilterRequest, 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]] = (), + ) -> subproperty_event_filter.SubpropertyEventFilter: + r"""Lookup for a single subproperty Event Filter. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.GetSubpropertyEventFilterRequest, dict]]): + The request object. Request message for + GetSubpropertyEventFilter RPC. + name (:class:`str`): + Required. Resource name of the subproperty event filter + to lookup. Format: + properties/property_id/subpropertyEventFilters/subproperty_event_filter + Example: properties/123/subpropertyEventFilters/456 + + 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.analytics.admin_v1alpha.types.SubpropertyEventFilter: + A resource message representing a GA4 + Subproperty event filter. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetSubpropertyEventFilterRequest): + request = analytics_admin.GetSubpropertyEventFilterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_subproperty_event_filter] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_subproperty_event_filters(self, + request: Optional[Union[analytics_admin.ListSubpropertyEventFiltersRequest, 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.ListSubpropertyEventFiltersAsyncPager: + r"""List all subproperty Event Filters on a property. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersRequest, dict]]): + The request object. Request message for + ListSubpropertyEventFilters RPC. + parent (:class:`str`): + Required. Resource name of the ordinary property. + Format: properties/property_id Example: properties/123 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSubpropertyEventFiltersAsyncPager: + Response message for + ListSubpropertyEventFilter RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListSubpropertyEventFiltersRequest): + request = analytics_admin.ListSubpropertyEventFiltersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_subproperty_event_filters] + + # Certain 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.ListSubpropertyEventFiltersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_subproperty_event_filter(self, + request: Optional[Union[analytics_admin.UpdateSubpropertyEventFilterRequest, dict]] = None, + *, + subproperty_event_filter: Optional[gaa_subproperty_event_filter.SubpropertyEventFilter] = 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]] = (), + ) -> gaa_subproperty_event_filter.SubpropertyEventFilter: + r"""Updates a subproperty Event Filter. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.UpdateSubpropertyEventFilterRequest, dict]]): + The request object. Request message for + UpdateSubpropertyEventFilter RPC. + subproperty_event_filter (:class:`google.analytics.admin_v1alpha.types.SubpropertyEventFilter`): + Required. The subproperty event + filter to update. + + This corresponds to the ``subproperty_event_filter`` 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 list of fields to update. Field names must + be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "*" to match + all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SubpropertyEventFilter: + A resource message representing a GA4 + Subproperty event filter. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subproperty_event_filter, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateSubpropertyEventFilterRequest): + request = analytics_admin.UpdateSubpropertyEventFilterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subproperty_event_filter is not None: + request.subproperty_event_filter = subproperty_event_filter + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_subproperty_event_filter] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("subproperty_event_filter.name", request.subproperty_event_filter.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_subproperty_event_filter(self, + request: Optional[Union[analytics_admin.DeleteSubpropertyEventFilterRequest, 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 subproperty event filter. + + Args: + request (Optional[Union[google.analytics.admin_v1alpha.types.DeleteSubpropertyEventFilterRequest, dict]]): + The request object. Request message for + DeleteSubpropertyEventFilter RPC. + name (:class:`str`): + Required. Resource name of the subproperty event filter + to delete. Format: + properties/property_id/subpropertyEventFilters/subproperty_event_filter + Example: properties/123/subpropertyEventFilters/456 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteSubpropertyEventFilterRequest): + request = analytics_admin.DeleteSubpropertyEventFilterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_subproperty_event_filter] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "AnalyticsAdminServiceAsyncClient": + 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__ = ( + "AnalyticsAdminServiceAsyncClient", +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py new file mode 100644 index 000000000000..becf37ce0801 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/client.py @@ -0,0 +1,12889 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.analytics.admin_v1alpha 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.analytics.admin_v1alpha.services.analytics_admin_service import pagers +from google.analytics.admin_v1alpha.types import access_report +from google.analytics.admin_v1alpha.types import analytics_admin +from google.analytics.admin_v1alpha.types import audience +from google.analytics.admin_v1alpha.types import audience as gaa_audience +from google.analytics.admin_v1alpha.types import channel_group +from google.analytics.admin_v1alpha.types import channel_group as gaa_channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set +from google.analytics.admin_v1alpha.types import expanded_data_set as gaa_expanded_data_set +from google.analytics.admin_v1alpha.types import resources +from google.analytics.admin_v1alpha.types import subproperty_event_filter +from google.analytics.admin_v1alpha.types import subproperty_event_filter as gaa_subproperty_event_filter +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 .transports.base import AnalyticsAdminServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AnalyticsAdminServiceGrpcTransport +from .transports.grpc_asyncio import AnalyticsAdminServiceGrpcAsyncIOTransport +from .transports.rest import AnalyticsAdminServiceRestTransport + + +class AnalyticsAdminServiceClientMeta(type): + """Metaclass for the AnalyticsAdminService 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[AnalyticsAdminServiceTransport]] + _transport_registry["grpc"] = AnalyticsAdminServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AnalyticsAdminServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AnalyticsAdminServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AnalyticsAdminServiceTransport]: + """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 AnalyticsAdminServiceClient(metaclass=AnalyticsAdminServiceClientMeta): + """Service Interface for the Analytics Admin API (GA4).""" + + @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 = "analyticsadmin.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "analyticsadmin.{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: + AnalyticsAdminServiceClient: 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: + AnalyticsAdminServiceClient: 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) -> AnalyticsAdminServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AnalyticsAdminServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def access_binding_path(account: str,access_binding: str,) -> str: + """Returns a fully-qualified access_binding string.""" + return "accounts/{account}/accessBindings/{access_binding}".format(account=account, access_binding=access_binding, ) + + @staticmethod + def parse_access_binding_path(path: str) -> Dict[str,str]: + """Parses a access_binding path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/accessBindings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def account_summary_path(account_summary: str,) -> str: + """Returns a fully-qualified account_summary string.""" + return "accountSummaries/{account_summary}".format(account_summary=account_summary, ) + + @staticmethod + def parse_account_summary_path(path: str) -> Dict[str,str]: + """Parses a account_summary path into its component segments.""" + m = re.match(r"^accountSummaries/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def ad_sense_link_path(property: str,adsense_link: str,) -> str: + """Returns a fully-qualified ad_sense_link string.""" + return "properties/{property}/adSenseLinks/{adsense_link}".format(property=property, adsense_link=adsense_link, ) + + @staticmethod + def parse_ad_sense_link_path(path: str) -> Dict[str,str]: + """Parses a ad_sense_link path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/adSenseLinks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def attribution_settings_path(property: str,) -> str: + """Returns a fully-qualified attribution_settings string.""" + return "properties/{property}/attributionSettings".format(property=property, ) + + @staticmethod + def parse_attribution_settings_path(path: str) -> Dict[str,str]: + """Parses a attribution_settings path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/attributionSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def audience_path(property: str,audience: str,) -> str: + """Returns a fully-qualified audience string.""" + return "properties/{property}/audiences/{audience}".format(property=property, audience=audience, ) + + @staticmethod + def parse_audience_path(path: str) -> Dict[str,str]: + """Parses a audience path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/audiences/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def big_query_link_path(property: str,bigquery_link: str,) -> str: + """Returns a fully-qualified big_query_link string.""" + return "properties/{property}/bigQueryLinks/{bigquery_link}".format(property=property, bigquery_link=bigquery_link, ) + + @staticmethod + def parse_big_query_link_path(path: str) -> Dict[str,str]: + """Parses a big_query_link path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/bigQueryLinks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def calculated_metric_path(property: str,calculated_metric: str,) -> str: + """Returns a fully-qualified calculated_metric string.""" + return "properties/{property}/calculatedMetrics/{calculated_metric}".format(property=property, calculated_metric=calculated_metric, ) + + @staticmethod + def parse_calculated_metric_path(path: str) -> Dict[str,str]: + """Parses a calculated_metric path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/calculatedMetrics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def channel_group_path(property: str,channel_group: str,) -> str: + """Returns a fully-qualified channel_group string.""" + return "properties/{property}/channelGroups/{channel_group}".format(property=property, channel_group=channel_group, ) + + @staticmethod + def parse_channel_group_path(path: str) -> Dict[str,str]: + """Parses a channel_group path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/channelGroups/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def conversion_event_path(property: str,conversion_event: str,) -> str: + """Returns a fully-qualified conversion_event string.""" + return "properties/{property}/conversionEvents/{conversion_event}".format(property=property, conversion_event=conversion_event, ) + + @staticmethod + def parse_conversion_event_path(path: str) -> Dict[str,str]: + """Parses a conversion_event path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/conversionEvents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def custom_dimension_path(property: str,custom_dimension: str,) -> str: + """Returns a fully-qualified custom_dimension string.""" + return "properties/{property}/customDimensions/{custom_dimension}".format(property=property, custom_dimension=custom_dimension, ) + + @staticmethod + def parse_custom_dimension_path(path: str) -> Dict[str,str]: + """Parses a custom_dimension path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/customDimensions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def custom_metric_path(property: str,custom_metric: str,) -> str: + """Returns a fully-qualified custom_metric string.""" + return "properties/{property}/customMetrics/{custom_metric}".format(property=property, custom_metric=custom_metric, ) + + @staticmethod + def parse_custom_metric_path(path: str) -> Dict[str,str]: + """Parses a custom_metric path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/customMetrics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_redaction_settings_path(property: str,data_stream: str,) -> str: + """Returns a fully-qualified data_redaction_settings string.""" + return "properties/{property}/dataStreams/{data_stream}/dataRedactionSettings".format(property=property, data_stream=data_stream, ) + + @staticmethod + def parse_data_redaction_settings_path(path: str) -> Dict[str,str]: + """Parses a data_redaction_settings path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)/dataRedactionSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_retention_settings_path(property: str,) -> str: + """Returns a fully-qualified data_retention_settings string.""" + return "properties/{property}/dataRetentionSettings".format(property=property, ) + + @staticmethod + def parse_data_retention_settings_path(path: str) -> Dict[str,str]: + """Parses a data_retention_settings path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataRetentionSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_sharing_settings_path(account: str,) -> str: + """Returns a fully-qualified data_sharing_settings string.""" + return "accounts/{account}/dataSharingSettings".format(account=account, ) + + @staticmethod + def parse_data_sharing_settings_path(path: str) -> Dict[str,str]: + """Parses a data_sharing_settings path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/dataSharingSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_stream_path(property: str,data_stream: str,) -> str: + """Returns a fully-qualified data_stream string.""" + return "properties/{property}/dataStreams/{data_stream}".format(property=property, data_stream=data_stream, ) + + @staticmethod + def parse_data_stream_path(path: str) -> Dict[str,str]: + """Parses a data_stream path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def display_video360_advertiser_link_path(property: str,display_video_360_advertiser_link: str,) -> str: + """Returns a fully-qualified display_video360_advertiser_link string.""" + return "properties/{property}/displayVideo360AdvertiserLinks/{display_video_360_advertiser_link}".format(property=property, display_video_360_advertiser_link=display_video_360_advertiser_link, ) + + @staticmethod + def parse_display_video360_advertiser_link_path(path: str) -> Dict[str,str]: + """Parses a display_video360_advertiser_link path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/displayVideo360AdvertiserLinks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def display_video360_advertiser_link_proposal_path(property: str,display_video_360_advertiser_link_proposal: str,) -> str: + """Returns a fully-qualified display_video360_advertiser_link_proposal string.""" + return "properties/{property}/displayVideo360AdvertiserLinkProposals/{display_video_360_advertiser_link_proposal}".format(property=property, display_video_360_advertiser_link_proposal=display_video_360_advertiser_link_proposal, ) + + @staticmethod + def parse_display_video360_advertiser_link_proposal_path(path: str) -> Dict[str,str]: + """Parses a display_video360_advertiser_link_proposal path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/displayVideo360AdvertiserLinkProposals/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def enhanced_measurement_settings_path(property: str,data_stream: str,) -> str: + """Returns a fully-qualified enhanced_measurement_settings string.""" + return "properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings".format(property=property, data_stream=data_stream, ) + + @staticmethod + def parse_enhanced_measurement_settings_path(path: str) -> Dict[str,str]: + """Parses a enhanced_measurement_settings path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)/enhancedMeasurementSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def event_create_rule_path(property: str,data_stream: str,event_create_rule: str,) -> str: + """Returns a fully-qualified event_create_rule string.""" + return "properties/{property}/dataStreams/{data_stream}/eventCreateRules/{event_create_rule}".format(property=property, data_stream=data_stream, event_create_rule=event_create_rule, ) + + @staticmethod + def parse_event_create_rule_path(path: str) -> Dict[str,str]: + """Parses a event_create_rule path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)/eventCreateRules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def event_edit_rule_path(property: str,data_stream: str,event_edit_rule: str,) -> str: + """Returns a fully-qualified event_edit_rule string.""" + return "properties/{property}/dataStreams/{data_stream}/eventEditRules/{event_edit_rule}".format(property=property, data_stream=data_stream, event_edit_rule=event_edit_rule, ) + + @staticmethod + def parse_event_edit_rule_path(path: str) -> Dict[str,str]: + """Parses a event_edit_rule path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)/eventEditRules/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def expanded_data_set_path(property: str,expanded_data_set: str,) -> str: + """Returns a fully-qualified expanded_data_set string.""" + return "properties/{property}/expandedDataSets/{expanded_data_set}".format(property=property, expanded_data_set=expanded_data_set, ) + + @staticmethod + def parse_expanded_data_set_path(path: str) -> Dict[str,str]: + """Parses a expanded_data_set path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/expandedDataSets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def firebase_link_path(property: str,firebase_link: str,) -> str: + """Returns a fully-qualified firebase_link string.""" + return "properties/{property}/firebaseLinks/{firebase_link}".format(property=property, firebase_link=firebase_link, ) + + @staticmethod + def parse_firebase_link_path(path: str) -> Dict[str,str]: + """Parses a firebase_link path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/firebaseLinks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def global_site_tag_path(property: str,data_stream: str,) -> str: + """Returns a fully-qualified global_site_tag string.""" + return "properties/{property}/dataStreams/{data_stream}/globalSiteTag".format(property=property, data_stream=data_stream, ) + + @staticmethod + def parse_global_site_tag_path(path: str) -> Dict[str,str]: + """Parses a global_site_tag path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)/globalSiteTag$", path) + return m.groupdict() if m else {} + + @staticmethod + def google_ads_link_path(property: str,google_ads_link: str,) -> str: + """Returns a fully-qualified google_ads_link string.""" + return "properties/{property}/googleAdsLinks/{google_ads_link}".format(property=property, google_ads_link=google_ads_link, ) + + @staticmethod + def parse_google_ads_link_path(path: str) -> Dict[str,str]: + """Parses a google_ads_link path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/googleAdsLinks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def google_signals_settings_path(property: str,) -> str: + """Returns a fully-qualified google_signals_settings string.""" + return "properties/{property}/googleSignalsSettings".format(property=property, ) + + @staticmethod + def parse_google_signals_settings_path(path: str) -> Dict[str,str]: + """Parses a google_signals_settings path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/googleSignalsSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def key_event_path(property: str,key_event: str,) -> str: + """Returns a fully-qualified key_event string.""" + return "properties/{property}/keyEvents/{key_event}".format(property=property, key_event=key_event, ) + + @staticmethod + def parse_key_event_path(path: str) -> Dict[str,str]: + """Parses a key_event path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/keyEvents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def measurement_protocol_secret_path(property: str,data_stream: str,measurement_protocol_secret: str,) -> str: + """Returns a fully-qualified measurement_protocol_secret string.""" + return "properties/{property}/dataStreams/{data_stream}/measurementProtocolSecrets/{measurement_protocol_secret}".format(property=property, data_stream=data_stream, measurement_protocol_secret=measurement_protocol_secret, ) + + @staticmethod + def parse_measurement_protocol_secret_path(path: str) -> Dict[str,str]: + """Parses a measurement_protocol_secret path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)/measurementProtocolSecrets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_path(organization: str,) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_organization_path(path: str) -> Dict[str,str]: + """Parses a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def property_path(property: str,) -> str: + """Returns a fully-qualified property string.""" + return "properties/{property}".format(property=property, ) + + @staticmethod + def parse_property_path(path: str) -> Dict[str,str]: + """Parses a property path into its component segments.""" + m = re.match(r"^properties/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def rollup_property_source_link_path(property: str,rollup_property_source_link: str,) -> str: + """Returns a fully-qualified rollup_property_source_link string.""" + return "properties/{property}/rollupPropertySourceLinks/{rollup_property_source_link}".format(property=property, rollup_property_source_link=rollup_property_source_link, ) + + @staticmethod + def parse_rollup_property_source_link_path(path: str) -> Dict[str,str]: + """Parses a rollup_property_source_link path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/rollupPropertySourceLinks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def search_ads360_link_path(property: str,search_ads_360_link: str,) -> str: + """Returns a fully-qualified search_ads360_link string.""" + return "properties/{property}/searchAds360Links/{search_ads_360_link}".format(property=property, search_ads_360_link=search_ads_360_link, ) + + @staticmethod + def parse_search_ads360_link_path(path: str) -> Dict[str,str]: + """Parses a search_ads360_link path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/searchAds360Links/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def sk_ad_network_conversion_value_schema_path(property: str,data_stream: str,skadnetwork_conversion_value_schema: str,) -> str: + """Returns a fully-qualified sk_ad_network_conversion_value_schema string.""" + return "properties/{property}/dataStreams/{data_stream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema}".format(property=property, data_stream=data_stream, skadnetwork_conversion_value_schema=skadnetwork_conversion_value_schema, ) + + @staticmethod + def parse_sk_ad_network_conversion_value_schema_path(path: str) -> Dict[str,str]: + """Parses a sk_ad_network_conversion_value_schema path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)/sKAdNetworkConversionValueSchema/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def subproperty_event_filter_path(property: str,sub_property_event_filter: str,) -> str: + """Returns a fully-qualified subproperty_event_filter string.""" + return "properties/{property}/subpropertyEventFilters/{sub_property_event_filter}".format(property=property, sub_property_event_filter=sub_property_event_filter, ) + + @staticmethod + def parse_subproperty_event_filter_path(path: str) -> Dict[str,str]: + """Parses a subproperty_event_filter path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/subpropertyEventFilters/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AnalyticsAdminServiceClient._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 = AnalyticsAdminServiceClient._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 = AnalyticsAdminServiceClient._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 + AnalyticsAdminServiceClient._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, AnalyticsAdminServiceTransport, Callable[..., AnalyticsAdminServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the analytics admin service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AnalyticsAdminServiceTransport,Callable[..., AnalyticsAdminServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AnalyticsAdminServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AnalyticsAdminServiceClient._read_environment_variables() + self._client_cert_source = AnalyticsAdminServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AnalyticsAdminServiceClient._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, AnalyticsAdminServiceTransport) + if transport_provided: + # transport is a AnalyticsAdminServiceTransport 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(AnalyticsAdminServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AnalyticsAdminServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AnalyticsAdminServiceTransport], Callable[..., AnalyticsAdminServiceTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AnalyticsAdminServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_account(self, + request: Optional[Union[analytics_admin.GetAccountRequest, 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]] = (), + ) -> resources.Account: + r"""Lookup for a single Account. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetAccountRequest, dict]): + The request object. Request message for GetAccount RPC. + name (str): + Required. The name of the account to + lookup. Format: accounts/{account} + Example: "accounts/100" + + 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.analytics.admin_v1alpha.types.Account: + A resource message representing a + Google Analytics account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAccountRequest): + request = analytics_admin.GetAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_accounts(self, + request: Optional[Union[analytics_admin.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAccountsPager: + r"""Returns all accounts accessible by the caller. + + Note that these accounts might not currently have GA4 + properties. Soft-deleted (ie: "trashed") accounts are + excluded by default. Returns an empty list if no + relevant accounts are found. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListAccountsRequest, dict]): + The request object. Request message for ListAccounts RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccountsPager: + Request message for ListAccounts RPC. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccountsRequest): + request = analytics_admin.ListAccountsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_accounts] + + # 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.ListAccountsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_account(self, + request: Optional[Union[analytics_admin.DeleteAccountRequest, 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"""Marks target Account as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + accounts. However, they can be restored using the Trash + Can UI. + + If the accounts are not restored before the expiration + time, the account and all child resources (eg: + Properties, GoogleAdsLinks, Streams, AccessBindings) + will be permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteAccountRequest, dict]): + The request object. Request message for DeleteAccount + RPC. + name (str): + Required. The name of the Account to + soft-delete. Format: accounts/{account} + Example: "accounts/100" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAccountRequest): + request = analytics_admin.DeleteAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_account] + + # Certain fields should be provided within 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 update_account(self, + request: Optional[Union[analytics_admin.UpdateAccountRequest, dict]] = None, + *, + account: Optional[resources.Account] = 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]] = (), + ) -> resources.Account: + r"""Updates an account. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateAccountRequest, dict]): + The request object. Request message for UpdateAccount + RPC. + account (google.analytics.admin_v1alpha.types.Account): + Required. The account to update. The account's ``name`` + field is used to identify the account. + + This corresponds to the ``account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "*" to match + all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Account: + A resource message representing a + Google Analytics account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([account, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAccountRequest): + request = analytics_admin.UpdateAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account is not None: + request.account = account + 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_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account.name", request.account.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 provision_account_ticket(self, + request: Optional[Union[analytics_admin.ProvisionAccountTicketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ProvisionAccountTicketResponse: + r"""Requests a ticket for creating an account. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ProvisionAccountTicketRequest, dict]): + The request object. Request message for + ProvisionAccountTicket RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ProvisionAccountTicketResponse: + Response message for + ProvisionAccountTicket RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ProvisionAccountTicketRequest): + request = analytics_admin.ProvisionAccountTicketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.provision_account_ticket] + + # 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_account_summaries(self, + request: Optional[Union[analytics_admin.ListAccountSummariesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAccountSummariesPager: + r"""Returns summaries of all accounts accessible by the + caller. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListAccountSummariesRequest, dict]): + The request object. Request message for + ListAccountSummaries RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccountSummariesPager: + Response message for + ListAccountSummaries RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccountSummariesRequest): + request = analytics_admin.ListAccountSummariesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_account_summaries] + + # 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.ListAccountSummariesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_property(self, + request: Optional[Union[analytics_admin.GetPropertyRequest, 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]] = (), + ) -> resources.Property: + r"""Lookup for a single "GA4" Property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetPropertyRequest, dict]): + The request object. Request message for GetProperty RPC. + name (str): + Required. The name of the property to lookup. Format: + properties/{property_id} Example: "properties/1000" + + 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.analytics.admin_v1alpha.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetPropertyRequest): + request = analytics_admin.GetPropertyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_property] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_properties(self, + request: Optional[Union[analytics_admin.ListPropertiesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPropertiesPager: + r"""Returns child Properties under the specified parent + Account. + Only "GA4" properties will be returned. + Properties will be excluded if the caller does not have + access. Soft-deleted (ie: "trashed") properties are + excluded by default. Returns an empty list if no + relevant properties are found. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListPropertiesRequest, dict]): + The request object. Request message for ListProperties + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListPropertiesPager: + Response message for ListProperties + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListPropertiesRequest): + request = analytics_admin.ListPropertiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_properties] + + # 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.ListPropertiesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_property(self, + request: Optional[Union[analytics_admin.CreatePropertyRequest, dict]] = None, + *, + property: Optional[resources.Property] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Property: + r"""Creates an "GA4" property with the specified location + and attributes. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreatePropertyRequest, dict]): + The request object. Request message for CreateProperty + RPC. + property (google.analytics.admin_v1alpha.types.Property): + Required. The property to create. + Note: the supplied property must specify + its parent. + + This corresponds to the ``property`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([property]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreatePropertyRequest): + request = analytics_admin.CreatePropertyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if property is not None: + request.property = property + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_property] + + # 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_property(self, + request: Optional[Union[analytics_admin.DeletePropertyRequest, 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]] = (), + ) -> resources.Property: + r"""Marks target Property as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + properties. However, they can be restored using the + Trash Can UI. + + If the properties are not restored before the expiration + time, the Property and all child resources (eg: + GoogleAdsLinks, Streams, AccessBindings) will be + permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found, or is not a + GA4 Property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeletePropertyRequest, dict]): + The request object. Request message for DeleteProperty + RPC. + name (str): + Required. The name of the Property to soft-delete. + Format: properties/{property_id} Example: + "properties/1000" + + 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.analytics.admin_v1alpha.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeletePropertyRequest): + request = analytics_admin.DeletePropertyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_property] + + # Certain fields should be provided within 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_property(self, + request: Optional[Union[analytics_admin.UpdatePropertyRequest, dict]] = None, + *, + property: Optional[resources.Property] = 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]] = (), + ) -> resources.Property: + r"""Updates a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdatePropertyRequest, dict]): + The request object. Request message for UpdateProperty + RPC. + property (google.analytics.admin_v1alpha.types.Property): + Required. The property to update. The property's + ``name`` field is used to identify the property to be + updated. + + This corresponds to the ``property`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([property, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdatePropertyRequest): + request = analytics_admin.UpdatePropertyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if property is not None: + request.property = property + 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_property] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property.name", request.property.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_firebase_link(self, + request: Optional[Union[analytics_admin.CreateFirebaseLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + firebase_link: Optional[resources.FirebaseLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.FirebaseLink: + r"""Creates a FirebaseLink. + + Properties can have at most one FirebaseLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateFirebaseLinkRequest, dict]): + The request object. Request message for + CreateFirebaseLink RPC + parent (str): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firebase_link (google.analytics.admin_v1alpha.types.FirebaseLink): + Required. The Firebase link to + create. + + This corresponds to the ``firebase_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.FirebaseLink: + A link between a GA4 property and a + Firebase project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, firebase_link]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateFirebaseLinkRequest): + request = analytics_admin.CreateFirebaseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if firebase_link is not None: + request.firebase_link = firebase_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_firebase_link] + + # Certain 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 delete_firebase_link(self, + request: Optional[Union[analytics_admin.DeleteFirebaseLinkRequest, 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 FirebaseLink on a property + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteFirebaseLinkRequest, dict]): + The request object. Request message for + DeleteFirebaseLink RPC + name (str): + Required. Format: + properties/{property_id}/firebaseLinks/{firebase_link_id} + + Example: ``properties/1234/firebaseLinks/5678`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteFirebaseLinkRequest): + request = analytics_admin.DeleteFirebaseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_firebase_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_firebase_links(self, + request: Optional[Union[analytics_admin.ListFirebaseLinksRequest, 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.ListFirebaseLinksPager: + r"""Lists FirebaseLinks on a property. + Properties can have at most one FirebaseLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListFirebaseLinksRequest, dict]): + The request object. Request message for ListFirebaseLinks + RPC + parent (str): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListFirebaseLinksPager: + Response message for + ListFirebaseLinks RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListFirebaseLinksRequest): + request = analytics_admin.ListFirebaseLinksRequest(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_firebase_links] + + # Certain 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.ListFirebaseLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_global_site_tag(self, + request: Optional[Union[analytics_admin.GetGlobalSiteTagRequest, 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]] = (), + ) -> resources.GlobalSiteTag: + r"""Returns the Site Tag for the specified web stream. + Site Tags are immutable singletons. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetGlobalSiteTagRequest, dict]): + The request object. Request message for GetGlobalSiteTag + RPC. + name (str): + Required. The name of the site tag to lookup. Note that + site tags are singletons and do not have unique IDs. + Format: + properties/{property_id}/dataStreams/{stream_id}/globalSiteTag + + Example: + ``properties/123/dataStreams/456/globalSiteTag`` + + 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.analytics.admin_v1alpha.types.GlobalSiteTag: + Read-only resource with the tag for + sending data from a website to a + DataStream. Only present for web + DataStream resources. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetGlobalSiteTagRequest): + request = analytics_admin.GetGlobalSiteTagRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_global_site_tag] + + # Certain fields should be provided within 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_google_ads_link(self, + request: Optional[Union[analytics_admin.CreateGoogleAdsLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_ads_link: Optional[resources.GoogleAdsLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.GoogleAdsLink: + r"""Creates a GoogleAdsLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateGoogleAdsLinkRequest, dict]): + The request object. Request message for + CreateGoogleAdsLink RPC + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_ads_link (google.analytics.admin_v1alpha.types.GoogleAdsLink): + Required. The GoogleAdsLink to + create. + + This corresponds to the ``google_ads_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, google_ads_link]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateGoogleAdsLinkRequest): + request = analytics_admin.CreateGoogleAdsLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if google_ads_link is not None: + request.google_ads_link = google_ads_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_google_ads_link] + + # Certain 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_google_ads_link(self, + request: Optional[Union[analytics_admin.UpdateGoogleAdsLinkRequest, dict]] = None, + *, + google_ads_link: Optional[resources.GoogleAdsLink] = 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]] = (), + ) -> resources.GoogleAdsLink: + r"""Updates a GoogleAdsLink on a property + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateGoogleAdsLinkRequest, dict]): + The request object. Request message for + UpdateGoogleAdsLink RPC + google_ads_link (google.analytics.admin_v1alpha.types.GoogleAdsLink): + The GoogleAdsLink to update + This corresponds to the ``google_ads_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_ads_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateGoogleAdsLinkRequest): + request = analytics_admin.UpdateGoogleAdsLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_ads_link is not None: + request.google_ads_link = google_ads_link + 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_google_ads_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_ads_link.name", request.google_ads_link.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_google_ads_link(self, + request: Optional[Union[analytics_admin.DeleteGoogleAdsLinkRequest, 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 GoogleAdsLink on a property + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteGoogleAdsLinkRequest, dict]): + The request object. Request message for + DeleteGoogleAdsLink RPC. + name (str): + Required. Example format: + properties/1234/googleAdsLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteGoogleAdsLinkRequest): + request = analytics_admin.DeleteGoogleAdsLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_google_ads_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_google_ads_links(self, + request: Optional[Union[analytics_admin.ListGoogleAdsLinksRequest, 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.ListGoogleAdsLinksPager: + r"""Lists GoogleAdsLinks on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListGoogleAdsLinksRequest, dict]): + The request object. Request message for + ListGoogleAdsLinks RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListGoogleAdsLinksPager: + Response message for + ListGoogleAdsLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListGoogleAdsLinksRequest): + request = analytics_admin.ListGoogleAdsLinksRequest(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_google_ads_links] + + # Certain 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.ListGoogleAdsLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_data_sharing_settings(self, + request: Optional[Union[analytics_admin.GetDataSharingSettingsRequest, 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]] = (), + ) -> resources.DataSharingSettings: + r"""Get data sharing settings on an account. + Data sharing settings are singletons. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetDataSharingSettingsRequest, dict]): + The request object. Request message for + GetDataSharingSettings RPC. + name (str): + Required. The name of the settings to lookup. Format: + accounts/{account}/dataSharingSettings + + Example: ``accounts/1000/dataSharingSettings`` + + 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.analytics.admin_v1alpha.types.DataSharingSettings: + A resource message representing data + sharing settings of a Google Analytics + account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataSharingSettingsRequest): + request = analytics_admin.GetDataSharingSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_data_sharing_settings] + + # Certain fields should be provided within 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_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.GetMeasurementProtocolSecretRequest, 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]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Lookup for a single "GA4" MeasurementProtocolSecret. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetMeasurementProtocolSecretRequest, dict]): + The request object. Request message for + GetMeasurementProtocolSecret RPC. + name (str): + Required. The name of the measurement + protocol secret to lookup. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + + 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.analytics.admin_v1alpha.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetMeasurementProtocolSecretRequest): + request = analytics_admin.GetMeasurementProtocolSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_measurement_protocol_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_measurement_protocol_secrets(self, + request: Optional[Union[analytics_admin.ListMeasurementProtocolSecretsRequest, 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.ListMeasurementProtocolSecretsPager: + r"""Returns child MeasurementProtocolSecrets under the + specified parent Property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsRequest, dict]): + The request object. Request message for + ListMeasurementProtocolSecret RPC + parent (str): + Required. The resource name of the + parent stream. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListMeasurementProtocolSecretsPager: + Response message for + ListMeasurementProtocolSecret RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListMeasurementProtocolSecretsRequest): + request = analytics_admin.ListMeasurementProtocolSecretsRequest(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_measurement_protocol_secrets] + + # Certain 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.ListMeasurementProtocolSecretsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.CreateMeasurementProtocolSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + measurement_protocol_secret: Optional[resources.MeasurementProtocolSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Creates a measurement protocol secret. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateMeasurementProtocolSecretRequest, dict]): + The request object. Request message for + CreateMeasurementProtocolSecret RPC + parent (str): + Required. The parent resource where + this secret will be created. Format: + properties/{property}/dataStreams/{dataStream} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + measurement_protocol_secret (google.analytics.admin_v1alpha.types.MeasurementProtocolSecret): + Required. The measurement protocol + secret to create. + + This corresponds to the ``measurement_protocol_secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, measurement_protocol_secret]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateMeasurementProtocolSecretRequest): + request = analytics_admin.CreateMeasurementProtocolSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if measurement_protocol_secret is not None: + request.measurement_protocol_secret = measurement_protocol_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_measurement_protocol_secret] + + # Certain 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 delete_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.DeleteMeasurementProtocolSecretRequest, 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 target MeasurementProtocolSecret. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteMeasurementProtocolSecretRequest, dict]): + The request object. Request message for + DeleteMeasurementProtocolSecret RPC + name (str): + Required. The name of the + MeasurementProtocolSecret to delete. + Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteMeasurementProtocolSecretRequest): + request = analytics_admin.DeleteMeasurementProtocolSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_measurement_protocol_secret] + + # Certain fields should be provided within 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 update_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.UpdateMeasurementProtocolSecretRequest, dict]] = None, + *, + measurement_protocol_secret: Optional[resources.MeasurementProtocolSecret] = 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]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Updates a measurement protocol secret. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateMeasurementProtocolSecretRequest, dict]): + The request object. Request message for + UpdateMeasurementProtocolSecret RPC + measurement_protocol_secret (google.analytics.admin_v1alpha.types.MeasurementProtocolSecret): + Required. The measurement protocol + secret to update. + + This corresponds to the ``measurement_protocol_secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be + updated. Omitted fields will not be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([measurement_protocol_secret, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateMeasurementProtocolSecretRequest): + request = analytics_admin.UpdateMeasurementProtocolSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if measurement_protocol_secret is not None: + request.measurement_protocol_secret = measurement_protocol_secret + 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_measurement_protocol_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("measurement_protocol_secret.name", request.measurement_protocol_secret.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 acknowledge_user_data_collection(self, + request: Optional[Union[analytics_admin.AcknowledgeUserDataCollectionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.AcknowledgeUserDataCollectionResponse: + r"""Acknowledges the terms of user data collection for + the specified property. + This acknowledgement must be completed (either in the + Google Analytics UI or through this API) before + MeasurementProtocolSecret resources may be created. + + Args: + request (Union[google.analytics.admin_v1alpha.types.AcknowledgeUserDataCollectionRequest, dict]): + The request object. Request message for + AcknowledgeUserDataCollection RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AcknowledgeUserDataCollectionResponse: + Response message for + AcknowledgeUserDataCollection RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.AcknowledgeUserDataCollectionRequest): + request = analytics_admin.AcknowledgeUserDataCollectionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.acknowledge_user_data_collection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # 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_sk_ad_network_conversion_value_schema(self, + request: Optional[Union[analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, 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]] = (), + ) -> resources.SKAdNetworkConversionValueSchema: + r"""Looks up a single SKAdNetworkConversionValueSchema. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetSKAdNetworkConversionValueSchemaRequest, dict]): + The request object. Request message for + GetSKAdNetworkConversionValueSchema RPC. + name (str): + Required. The resource name of SKAdNetwork conversion + value schema to look up. Format: + properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} + + 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.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema: + SKAdNetwork conversion value schema + of an iOS stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetSKAdNetworkConversionValueSchemaRequest): + request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sk_ad_network_conversion_value_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_sk_ad_network_conversion_value_schema(self, + request: Optional[Union[analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + skadnetwork_conversion_value_schema: Optional[resources.SKAdNetworkConversionValueSchema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SKAdNetworkConversionValueSchema: + r"""Creates a SKAdNetworkConversionValueSchema. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateSKAdNetworkConversionValueSchemaRequest, dict]): + The request object. Request message for + CreateSKAdNetworkConversionValueSchema + RPC. + parent (str): + Required. The parent resource where + this schema will be created. Format: + properties/{property}/dataStreams/{dataStream} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + skadnetwork_conversion_value_schema (google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema): + Required. SKAdNetwork conversion + value schema to create. + + This corresponds to the ``skadnetwork_conversion_value_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema: + SKAdNetwork conversion value schema + of an iOS stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, skadnetwork_conversion_value_schema]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest): + request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if skadnetwork_conversion_value_schema is not None: + request.skadnetwork_conversion_value_schema = skadnetwork_conversion_value_schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sk_ad_network_conversion_value_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_sk_ad_network_conversion_value_schema(self, + request: Optional[Union[analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, 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 target SKAdNetworkConversionValueSchema. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteSKAdNetworkConversionValueSchemaRequest, dict]): + The request object. Request message for + DeleteSKAdNetworkConversionValueSchema + RPC. + name (str): + Required. The name of the + SKAdNetworkConversionValueSchema to delete. Format: + properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest): + request = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_sk_ad_network_conversion_value_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_sk_ad_network_conversion_value_schema(self, + request: Optional[Union[analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, dict]] = None, + *, + skadnetwork_conversion_value_schema: Optional[resources.SKAdNetworkConversionValueSchema] = 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]] = (), + ) -> resources.SKAdNetworkConversionValueSchema: + r"""Updates a SKAdNetworkConversionValueSchema. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateSKAdNetworkConversionValueSchemaRequest, dict]): + The request object. Request message for + UpdateSKAdNetworkConversionValueSchema + RPC. + skadnetwork_conversion_value_schema (google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema): + Required. SKAdNetwork conversion + value schema to update. + + This corresponds to the ``skadnetwork_conversion_value_schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be + updated. Omitted fields will not be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema: + SKAdNetwork conversion value schema + of an iOS stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([skadnetwork_conversion_value_schema, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest): + request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if skadnetwork_conversion_value_schema is not None: + request.skadnetwork_conversion_value_schema = skadnetwork_conversion_value_schema + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_sk_ad_network_conversion_value_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("skadnetwork_conversion_value_schema.name", request.skadnetwork_conversion_value_schema.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sk_ad_network_conversion_value_schemas(self, + request: Optional[Union[analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, 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.ListSKAdNetworkConversionValueSchemasPager: + r"""Lists SKAdNetworkConversionValueSchema on a stream. + Properties can have at most one + SKAdNetworkConversionValueSchema. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasRequest, dict]): + The request object. Request message for + ListSKAdNetworkConversionValueSchemas + RPC + parent (str): + Required. The DataStream resource to list schemas for. + Format: + properties/{property_id}/dataStreams/{dataStream} + Example: properties/1234/dataStreams/5678 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSKAdNetworkConversionValueSchemasPager: + Response message for + ListSKAdNetworkConversionValueSchemas + RPC Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListSKAdNetworkConversionValueSchemasRequest): + request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest(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_sk_ad_network_conversion_value_schemas] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSKAdNetworkConversionValueSchemasPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_change_history_events(self, + request: Optional[Union[analytics_admin.SearchChangeHistoryEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchChangeHistoryEventsPager: + r"""Searches through all changes to an account or its + children given the specified set of filters. + + Args: + request (Union[google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsRequest, dict]): + The request object. Request message for + SearchChangeHistoryEvents RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.services.analytics_admin_service.pagers.SearchChangeHistoryEventsPager: + Response message for SearchAccounts + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.SearchChangeHistoryEventsRequest): + request = analytics_admin.SearchChangeHistoryEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_change_history_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account", request.account), + )), + ) + + # 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.SearchChangeHistoryEventsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_google_signals_settings(self, + request: Optional[Union[analytics_admin.GetGoogleSignalsSettingsRequest, 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]] = (), + ) -> resources.GoogleSignalsSettings: + r"""Lookup for Google Signals settings for a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetGoogleSignalsSettingsRequest, dict]): + The request object. Request message for + GetGoogleSignalsSettings RPC + name (str): + Required. The name of the google + signals settings to retrieve. Format: + properties/{property}/googleSignalsSettings + + 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.analytics.admin_v1alpha.types.GoogleSignalsSettings: + Settings values for Google Signals. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetGoogleSignalsSettingsRequest): + request = analytics_admin.GetGoogleSignalsSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_google_signals_settings] + + # Certain fields should be provided within 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_google_signals_settings(self, + request: Optional[Union[analytics_admin.UpdateGoogleSignalsSettingsRequest, dict]] = None, + *, + google_signals_settings: Optional[resources.GoogleSignalsSettings] = 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]] = (), + ) -> resources.GoogleSignalsSettings: + r"""Updates Google Signals settings for a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateGoogleSignalsSettingsRequest, dict]): + The request object. Request message for + UpdateGoogleSignalsSettings RPC + google_signals_settings (google.analytics.admin_v1alpha.types.GoogleSignalsSettings): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``google_signals_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.GoogleSignalsSettings: + Settings values for Google Signals. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_signals_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateGoogleSignalsSettingsRequest): + request = analytics_admin.UpdateGoogleSignalsSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_signals_settings is not None: + request.google_signals_settings = google_signals_settings + 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_google_signals_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_signals_settings.name", request.google_signals_settings.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_conversion_event(self, + request: Optional[Union[analytics_admin.CreateConversionEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversion_event: Optional[resources.ConversionEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateConversionEventRequest, dict]): + The request object. Request message for + CreateConversionEvent RPC + parent (str): + Required. The resource name of the + parent property where this conversion + event will be created. Format: + properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversion_event (google.analytics.admin_v1alpha.types.ConversionEvent): + Required. The conversion event to + create. + + This corresponds to the ``conversion_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceClient.create_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversion_event]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateConversionEventRequest): + request = analytics_admin.CreateConversionEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversion_event is not None: + request.conversion_event = conversion_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_conversion_event(self, + request: Optional[Union[analytics_admin.UpdateConversionEventRequest, dict]] = None, + *, + conversion_event: Optional[resources.ConversionEvent] = 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]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateConversionEventRequest, dict]): + The request object. Request message for + UpdateConversionEvent RPC + conversion_event (google.analytics.admin_v1alpha.types.ConversionEvent): + Required. The conversion event to update. The ``name`` + field is used to identify the settings to be updated. + + This corresponds to the ``conversion_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceClient.update_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversion_event, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateConversionEventRequest): + request = analytics_admin.UpdateConversionEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversion_event is not None: + request.conversion_event = conversion_event + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversion_event.name", request.conversion_event.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_conversion_event(self, + request: Optional[Union[analytics_admin.GetConversionEventRequest, 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]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetConversionEventRequest, dict]): + The request object. Request message for + GetConversionEvent RPC + name (str): + Required. The resource name of the conversion event to + retrieve. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456" + + 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.analytics.admin_v1alpha.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceClient.get_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetConversionEventRequest): + request = analytics_admin.GetConversionEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_conversion_event(self, + request: Optional[Union[analytics_admin.DeleteConversionEventRequest, 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"""Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteConversionEventRequest, dict]): + The request object. Request message for + DeleteConversionEvent RPC + name (str): + Required. The resource name of the conversion event to + delete. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456" + + 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. + """ + warnings.warn("AnalyticsAdminServiceClient.delete_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteConversionEventRequest): + request = analytics_admin.DeleteConversionEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_conversion_events(self, + request: Optional[Union[analytics_admin.ListConversionEventsRequest, 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.ListConversionEventsPager: + r"""Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + + Returns an empty list if no conversion events are found. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListConversionEventsRequest, dict]): + The request object. Request message for + ListConversionEvents RPC + parent (str): + Required. The resource name of the + parent property. Example: + 'properties/123' + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListConversionEventsPager: + Response message for + ListConversionEvents RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("AnalyticsAdminServiceClient.list_conversion_events is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListConversionEventsRequest): + request = analytics_admin.ListConversionEventsRequest(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_conversion_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListConversionEventsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_key_event(self, + request: Optional[Union[analytics_admin.CreateKeyEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + key_event: Optional[resources.KeyEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyEvent: + r"""Creates a Key Event. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateKeyEventRequest, dict]): + The request object. Request message for CreateKeyEvent + RPC + parent (str): + Required. The resource name of the + parent property where this Key Event + will be created. Format: properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_event (google.analytics.admin_v1alpha.types.KeyEvent): + Required. The Key Event to create. + This corresponds to the ``key_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, key_event]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateKeyEventRequest): + request = analytics_admin.CreateKeyEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_event is not None: + request.key_event = key_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_key_event(self, + request: Optional[Union[analytics_admin.UpdateKeyEventRequest, dict]] = None, + *, + key_event: Optional[resources.KeyEvent] = 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]] = (), + ) -> resources.KeyEvent: + r"""Updates a Key Event. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateKeyEventRequest, dict]): + The request object. Request message for UpdateKeyEvent + RPC + key_event (google.analytics.admin_v1alpha.types.KeyEvent): + Required. The Key Event to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``key_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([key_event, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateKeyEventRequest): + request = analytics_admin.UpdateKeyEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if key_event is not None: + request.key_event = key_event + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("key_event.name", request.key_event.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_key_event(self, + request: Optional[Union[analytics_admin.GetKeyEventRequest, 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]] = (), + ) -> resources.KeyEvent: + r"""Retrieve a single Key Event. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetKeyEventRequest, dict]): + The request object. Request message for GetKeyEvent RPC + name (str): + Required. The resource name of the Key Event to + retrieve. Format: + properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456" + + 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.analytics.admin_v1alpha.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetKeyEventRequest): + request = analytics_admin.GetKeyEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_key_event(self, + request: Optional[Union[analytics_admin.DeleteKeyEventRequest, 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 Key Event. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteKeyEventRequest, dict]): + The request object. Request message for DeleteKeyEvent + RPC + name (str): + Required. The resource name of the Key Event to delete. + Format: properties/{property}/keyEvents/{key_event} + Example: "properties/123/keyEvents/456" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteKeyEventRequest): + request = analytics_admin.DeleteKeyEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_key_events(self, + request: Optional[Union[analytics_admin.ListKeyEventsRequest, 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.ListKeyEventsPager: + r"""Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListKeyEventsRequest, dict]): + The request object. Request message for ListKeyEvents RPC + parent (str): + Required. The resource name of the + parent property. Example: + 'properties/123' + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListKeyEventsPager: + Response message for ListKeyEvents + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListKeyEventsRequest): + request = analytics_admin.ListKeyEventsRequest(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_key_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListKeyEventsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_display_video360_advertiser_link(self, + request: Optional[Union[analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, 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]] = (), + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Look up a single DisplayVideo360AdvertiserLink + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkRequest, dict]): + The request object. Request message for + GetDisplayVideo360AdvertiserLink RPC. + name (str): + Required. The name of the + DisplayVideo360AdvertiserLink to get. + Example format: + properties/1234/displayVideo360AdvertiserLink/5678 + + 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.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDisplayVideo360AdvertiserLinkRequest): + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_display_video360_advertiser_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_display_video360_advertiser_links(self, + request: Optional[Union[analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, 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.ListDisplayVideo360AdvertiserLinksPager: + r"""Lists all DisplayVideo360AdvertiserLinks on a + property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksRequest, dict]): + The request object. Request message for + ListDisplayVideo360AdvertiserLinks RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinksPager: + Response message for + ListDisplayVideo360AdvertiserLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListDisplayVideo360AdvertiserLinksRequest): + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(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_display_video360_advertiser_links] + + # Certain 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.ListDisplayVideo360AdvertiserLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_display_video360_advertiser_link(self, + request: Optional[Union[analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + display_video_360_advertiser_link: Optional[resources.DisplayVideo360AdvertiserLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Creates a DisplayVideo360AdvertiserLink. + This can only be utilized by users who have proper + authorization both on the Google Analytics property and + on the Display & Video 360 advertiser. Users who do not + have access to the Display & Video 360 advertiser should + instead seek to create a DisplayVideo360LinkProposal. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkRequest, dict]): + The request object. Request message for + CreateDisplayVideo360AdvertiserLink RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): + Required. The + DisplayVideo360AdvertiserLink to create. + + This corresponds to the ``display_video_360_advertiser_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, display_video_360_advertiser_link]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest): + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if display_video_360_advertiser_link is not None: + request.display_video_360_advertiser_link = display_video_360_advertiser_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_display_video360_advertiser_link] + + # Certain 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 delete_display_video360_advertiser_link(self, + request: Optional[Union[analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, 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 DisplayVideo360AdvertiserLink on a + property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkRequest, dict]): + The request object. Request message for + DeleteDisplayVideo360AdvertiserLink RPC. + name (str): + Required. The name of the + DisplayVideo360AdvertiserLink to delete. + Example format: + properties/1234/displayVideo360AdvertiserLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest): + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_display_video360_advertiser_link] + + # Certain fields should be provided within 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 update_display_video360_advertiser_link(self, + request: Optional[Union[analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, dict]] = None, + *, + display_video_360_advertiser_link: Optional[resources.DisplayVideo360AdvertiserLink] = 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]] = (), + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Updates a DisplayVideo360AdvertiserLink on a + property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateDisplayVideo360AdvertiserLinkRequest, dict]): + The request object. Request message for + UpdateDisplayVideo360AdvertiserLink RPC. + display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): + The DisplayVideo360AdvertiserLink to + update + + This corresponds to the ``display_video_360_advertiser_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([display_video_360_advertiser_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest): + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if display_video_360_advertiser_link is not None: + request.display_video_360_advertiser_link = display_video_360_advertiser_link + 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_display_video360_advertiser_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("display_video_360_advertiser_link.name", request.display_video_360_advertiser_link.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_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, 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]] = (), + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Lookup for a single + DisplayVideo360AdvertiserLinkProposal. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetDisplayVideo360AdvertiserLinkProposalRequest, dict]): + The request object. Request message for + GetDisplayVideo360AdvertiserLinkProposal + RPC. + name (str): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to + get. Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + + 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.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_display_video360_advertiser_link_proposal] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_display_video360_advertiser_link_proposals(self, + request: Optional[Union[analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, 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.ListDisplayVideo360AdvertiserLinkProposalsPager: + r"""Lists DisplayVideo360AdvertiserLinkProposals on a + property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsRequest, dict]): + The request object. Request message for + ListDisplayVideo360AdvertiserLinkProposals + RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDisplayVideo360AdvertiserLinkProposalsPager: + Response message for + ListDisplayVideo360AdvertiserLinkProposals + RPC. Iterating over this object will + yield results and resolve additional + pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest): + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(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_display_video360_advertiser_link_proposals] + + # Certain 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.ListDisplayVideo360AdvertiserLinkProposalsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict]] = None, + *, + parent: Optional[str] = None, + display_video_360_advertiser_link_proposal: Optional[resources.DisplayVideo360AdvertiserLinkProposal] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Creates a DisplayVideo360AdvertiserLinkProposal. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateDisplayVideo360AdvertiserLinkProposalRequest, dict]): + The request object. Request message for + CreateDisplayVideo360AdvertiserLinkProposal + RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_video_360_advertiser_link_proposal (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal): + Required. The + DisplayVideo360AdvertiserLinkProposal to + create. + + This corresponds to the ``display_video_360_advertiser_link_proposal`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, display_video_360_advertiser_link_proposal]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if display_video_360_advertiser_link_proposal is not None: + request.display_video_360_advertiser_link_proposal = display_video_360_advertiser_link_proposal + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_display_video360_advertiser_link_proposal] + + # Certain 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 delete_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, 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 DisplayVideo360AdvertiserLinkProposal on a + property. This can only be used on cancelled proposals. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteDisplayVideo360AdvertiserLinkProposalRequest, dict]): + The request object. Request message for + DeleteDisplayVideo360AdvertiserLinkProposal + RPC. + name (str): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to + delete. Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_display_video360_advertiser_link_proposal] + + # Certain fields should be provided within 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 approve_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + r"""Approves a DisplayVideo360AdvertiserLinkProposal. + The DisplayVideo360AdvertiserLinkProposal will be + deleted and a new DisplayVideo360AdvertiserLink will be + created. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalRequest, dict]): + The request object. Request message for + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + Response message for + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.approve_display_video360_advertiser_link_proposal] + + # Certain fields should be provided within 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 cancel_display_video360_advertiser_link_proposal(self, + request: Optional[Union[analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Cancels a DisplayVideo360AdvertiserLinkProposal. + Cancelling can mean either: + + - Declining a proposal initiated from Display & Video + 360 + - Withdrawing a proposal initiated from Google Analytics + After being cancelled, a proposal will eventually be + deleted automatically. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CancelDisplayVideo360AdvertiserLinkProposalRequest, dict]): + The request object. Request message for + CancelDisplayVideo360AdvertiserLinkProposal + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest): + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_display_video360_advertiser_link_proposal] + + # Certain fields should be provided within 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_custom_dimension(self, + request: Optional[Union[analytics_admin.CreateCustomDimensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_dimension: Optional[resources.CustomDimension] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CustomDimension: + r"""Creates a CustomDimension. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateCustomDimensionRequest, dict]): + The request object. Request message for + CreateCustomDimension RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_dimension (google.analytics.admin_v1alpha.types.CustomDimension): + Required. The CustomDimension to + create. + + This corresponds to the ``custom_dimension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_dimension]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCustomDimensionRequest): + request = analytics_admin.CreateCustomDimensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_dimension is not None: + request.custom_dimension = custom_dimension + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_custom_dimension] + + # Certain 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_custom_dimension(self, + request: Optional[Union[analytics_admin.UpdateCustomDimensionRequest, dict]] = None, + *, + custom_dimension: Optional[resources.CustomDimension] = 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]] = (), + ) -> resources.CustomDimension: + r"""Updates a CustomDimension on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateCustomDimensionRequest, dict]): + The request object. Request message for + UpdateCustomDimension RPC. + custom_dimension (google.analytics.admin_v1alpha.types.CustomDimension): + The CustomDimension to update + This corresponds to the ``custom_dimension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_dimension, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCustomDimensionRequest): + request = analytics_admin.UpdateCustomDimensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_dimension is not None: + request.custom_dimension = custom_dimension + 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_custom_dimension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("custom_dimension.name", request.custom_dimension.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_custom_dimensions(self, + request: Optional[Union[analytics_admin.ListCustomDimensionsRequest, 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.ListCustomDimensionsPager: + r"""Lists CustomDimensions on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListCustomDimensionsRequest, dict]): + The request object. Request message for + ListCustomDimensions RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomDimensionsPager: + Response message for + ListCustomDimensions RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCustomDimensionsRequest): + request = analytics_admin.ListCustomDimensionsRequest(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_custom_dimensions] + + # Certain 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.ListCustomDimensionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def archive_custom_dimension(self, + request: Optional[Union[analytics_admin.ArchiveCustomDimensionRequest, 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"""Archives a CustomDimension on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ArchiveCustomDimensionRequest, dict]): + The request object. Request message for + ArchiveCustomDimension RPC. + name (str): + Required. The name of the + CustomDimension to archive. Example + format: + properties/1234/customDimensions/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveCustomDimensionRequest): + request = analytics_admin.ArchiveCustomDimensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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.archive_custom_dimension] + + # Certain fields should be provided within 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_custom_dimension(self, + request: Optional[Union[analytics_admin.GetCustomDimensionRequest, 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]] = (), + ) -> resources.CustomDimension: + r"""Lookup for a single CustomDimension. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetCustomDimensionRequest, dict]): + The request object. Request message for + GetCustomDimension RPC. + name (str): + Required. The name of the + CustomDimension to get. Example format: + properties/1234/customDimensions/5678 + + 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.analytics.admin_v1alpha.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCustomDimensionRequest): + request = analytics_admin.GetCustomDimensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_custom_dimension] + + # Certain fields should be provided within 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_custom_metric(self, + request: Optional[Union[analytics_admin.CreateCustomMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_metric: Optional[resources.CustomMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CustomMetric: + r"""Creates a CustomMetric. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateCustomMetricRequest, dict]): + The request object. Request message for + CreateCustomMetric RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_metric (google.analytics.admin_v1alpha.types.CustomMetric): + Required. The CustomMetric to create. + This corresponds to the ``custom_metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_metric]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCustomMetricRequest): + request = analytics_admin.CreateCustomMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_metric is not None: + request.custom_metric = custom_metric + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_custom_metric] + + # Certain 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_custom_metric(self, + request: Optional[Union[analytics_admin.UpdateCustomMetricRequest, dict]] = None, + *, + custom_metric: Optional[resources.CustomMetric] = 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]] = (), + ) -> resources.CustomMetric: + r"""Updates a CustomMetric on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateCustomMetricRequest, dict]): + The request object. Request message for + UpdateCustomMetric RPC. + custom_metric (google.analytics.admin_v1alpha.types.CustomMetric): + The CustomMetric to update + This corresponds to the ``custom_metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_metric, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCustomMetricRequest): + request = analytics_admin.UpdateCustomMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_metric is not None: + request.custom_metric = custom_metric + 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_custom_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("custom_metric.name", request.custom_metric.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_custom_metrics(self, + request: Optional[Union[analytics_admin.ListCustomMetricsRequest, 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.ListCustomMetricsPager: + r"""Lists CustomMetrics on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListCustomMetricsRequest, dict]): + The request object. Request message for ListCustomMetrics + RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCustomMetricsPager: + Response message for + ListCustomMetrics RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCustomMetricsRequest): + request = analytics_admin.ListCustomMetricsRequest(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_custom_metrics] + + # Certain 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.ListCustomMetricsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def archive_custom_metric(self, + request: Optional[Union[analytics_admin.ArchiveCustomMetricRequest, 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"""Archives a CustomMetric on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ArchiveCustomMetricRequest, dict]): + The request object. Request message for + ArchiveCustomMetric RPC. + name (str): + Required. The name of the + CustomMetric to archive. Example format: + properties/1234/customMetrics/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveCustomMetricRequest): + request = analytics_admin.ArchiveCustomMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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.archive_custom_metric] + + # Certain fields should be provided within 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_custom_metric(self, + request: Optional[Union[analytics_admin.GetCustomMetricRequest, 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]] = (), + ) -> resources.CustomMetric: + r"""Lookup for a single CustomMetric. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetCustomMetricRequest, dict]): + The request object. Request message for GetCustomMetric + RPC. + name (str): + Required. The name of the + CustomMetric to get. Example format: + properties/1234/customMetrics/5678 + + 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.analytics.admin_v1alpha.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCustomMetricRequest): + request = analytics_admin.GetCustomMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_custom_metric] + + # Certain fields should be provided within 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_data_retention_settings(self, + request: Optional[Union[analytics_admin.GetDataRetentionSettingsRequest, 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]] = (), + ) -> resources.DataRetentionSettings: + r"""Returns the singleton data retention settings for + this property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetDataRetentionSettingsRequest, dict]): + The request object. Request message for + GetDataRetentionSettings RPC. + name (str): + Required. The name of the settings to + lookup. Format: + + properties/{property}/dataRetentionSettings + Example: + "properties/1000/dataRetentionSettings" + + 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.analytics.admin_v1alpha.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataRetentionSettingsRequest): + request = analytics_admin.GetDataRetentionSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_data_retention_settings] + + # Certain fields should be provided within 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_data_retention_settings(self, + request: Optional[Union[analytics_admin.UpdateDataRetentionSettingsRequest, dict]] = None, + *, + data_retention_settings: Optional[resources.DataRetentionSettings] = 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]] = (), + ) -> resources.DataRetentionSettings: + r"""Updates the singleton data retention settings for + this property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateDataRetentionSettingsRequest, dict]): + The request object. Request message for + UpdateDataRetentionSettings RPC. + data_retention_settings (google.analytics.admin_v1alpha.types.DataRetentionSettings): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``data_retention_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_retention_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataRetentionSettingsRequest): + request = analytics_admin.UpdateDataRetentionSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_retention_settings is not None: + request.data_retention_settings = data_retention_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_data_retention_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_retention_settings.name", request.data_retention_settings.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_data_stream(self, + request: Optional[Union[analytics_admin.CreateDataStreamRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_stream: Optional[resources.DataStream] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DataStream: + r"""Creates a DataStream. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateDataStreamRequest, dict]): + The request object. Request message for CreateDataStream + RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_stream (google.analytics.admin_v1alpha.types.DataStream): + Required. The DataStream to create. + This corresponds to the ``data_stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_stream]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateDataStreamRequest): + request = analytics_admin.CreateDataStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_stream is not None: + request.data_stream = data_stream + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_data_stream(self, + request: Optional[Union[analytics_admin.DeleteDataStreamRequest, 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 DataStream on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteDataStreamRequest, dict]): + The request object. Request message for DeleteDataStream + RPC. + name (str): + Required. The name of the DataStream + to delete. Example format: + properties/1234/dataStreams/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteDataStreamRequest): + request = analytics_admin.DeleteDataStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_data_stream(self, + request: Optional[Union[analytics_admin.UpdateDataStreamRequest, dict]] = None, + *, + data_stream: Optional[resources.DataStream] = 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]] = (), + ) -> resources.DataStream: + r"""Updates a DataStream on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateDataStreamRequest, dict]): + The request object. Request message for UpdateDataStream + RPC. + data_stream (google.analytics.admin_v1alpha.types.DataStream): + The DataStream to update + This corresponds to the ``data_stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_stream, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataStreamRequest): + request = analytics_admin.UpdateDataStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_stream is not None: + request.data_stream = data_stream + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_stream.name", request.data_stream.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_data_streams(self, + request: Optional[Union[analytics_admin.ListDataStreamsRequest, 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.ListDataStreamsPager: + r"""Lists DataStreams on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListDataStreamsRequest, dict]): + The request object. Request message for ListDataStreams + RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListDataStreamsPager: + Response message for ListDataStreams + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListDataStreamsRequest): + request = analytics_admin.ListDataStreamsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_data_streams] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDataStreamsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_data_stream(self, + request: Optional[Union[analytics_admin.GetDataStreamRequest, 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]] = (), + ) -> resources.DataStream: + r"""Lookup for a single DataStream. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetDataStreamRequest, dict]): + The request object. Request message for GetDataStream + RPC. + name (str): + Required. The name of the DataStream + to get. Example format: + properties/1234/dataStreams/5678 + + 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.analytics.admin_v1alpha.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataStreamRequest): + request = analytics_admin.GetDataStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_audience(self, + request: Optional[Union[analytics_admin.GetAudienceRequest, 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]] = (), + ) -> audience.Audience: + r"""Lookup for a single Audience. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetAudienceRequest, dict]): + The request object. Request message for GetAudience RPC. + name (str): + Required. The name of the Audience to + get. Example format: + properties/1234/audiences/5678 + + 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.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAudienceRequest): + request = analytics_admin.GetAudienceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_audience] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_audiences(self, + request: Optional[Union[analytics_admin.ListAudiencesRequest, 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.ListAudiencesPager: + r"""Lists Audiences on a property. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListAudiencesRequest, dict]): + The request object. Request message for ListAudiences + RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAudiencesPager: + Response message for ListAudiences + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAudiencesRequest): + request = analytics_admin.ListAudiencesRequest(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_audiences] + + # Certain 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.ListAudiencesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_audience(self, + request: Optional[Union[analytics_admin.CreateAudienceRequest, dict]] = None, + *, + parent: Optional[str] = None, + audience: Optional[gaa_audience.Audience] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gaa_audience.Audience: + r"""Creates an Audience. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateAudienceRequest, dict]): + The request object. Request message for CreateAudience + RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audience (google.analytics.admin_v1alpha.types.Audience): + Required. The audience to create. + This corresponds to the ``audience`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, audience]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateAudienceRequest): + request = analytics_admin.CreateAudienceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if audience is not None: + request.audience = audience + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_audience] + + # Certain 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_audience(self, + request: Optional[Union[analytics_admin.UpdateAudienceRequest, dict]] = None, + *, + audience: Optional[gaa_audience.Audience] = 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]] = (), + ) -> gaa_audience.Audience: + r"""Updates an Audience on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateAudienceRequest, dict]): + The request object. Request message for UpdateAudience + RPC. + audience (google.analytics.admin_v1alpha.types.Audience): + Required. The audience to update. The audience's + ``name`` field is used to identify the audience to be + updated. + + This corresponds to the ``audience`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.Audience: + A resource message representing a GA4 + Audience. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([audience, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAudienceRequest): + request = analytics_admin.UpdateAudienceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if audience is not None: + request.audience = audience + 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_audience] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("audience.name", request.audience.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 archive_audience(self, + request: Optional[Union[analytics_admin.ArchiveAudienceRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Archives an Audience on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ArchiveAudienceRequest, dict]): + The request object. Request message for ArchiveAudience + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveAudienceRequest): + request = analytics_admin.ArchiveAudienceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.archive_audience] + + # Certain fields should be provided within 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_search_ads360_link(self, + request: Optional[Union[analytics_admin.GetSearchAds360LinkRequest, 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]] = (), + ) -> resources.SearchAds360Link: + r"""Look up a single SearchAds360Link + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetSearchAds360LinkRequest, dict]): + The request object. Request message for + GetSearchAds360Link RPC. + name (str): + Required. The name of the + SearchAds360Link to get. Example format: + properties/1234/SearchAds360Link/5678 + + 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.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetSearchAds360LinkRequest): + request = analytics_admin.GetSearchAds360LinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_search_ads360_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_search_ads360_links(self, + request: Optional[Union[analytics_admin.ListSearchAds360LinksRequest, 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.ListSearchAds360LinksPager: + r"""Lists all SearchAds360Links on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListSearchAds360LinksRequest, dict]): + The request object. Request message for + ListSearchAds360Links RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSearchAds360LinksPager: + Response message for + ListSearchAds360Links RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListSearchAds360LinksRequest): + request = analytics_admin.ListSearchAds360LinksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_search_ads360_links] + + # Certain 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.ListSearchAds360LinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_search_ads360_link(self, + request: Optional[Union[analytics_admin.CreateSearchAds360LinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + search_ads_360_link: Optional[resources.SearchAds360Link] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.SearchAds360Link: + r"""Creates a SearchAds360Link. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateSearchAds360LinkRequest, dict]): + The request object. Request message for + CreateSearchAds360Link RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + search_ads_360_link (google.analytics.admin_v1alpha.types.SearchAds360Link): + Required. The SearchAds360Link to + create. + + This corresponds to the ``search_ads_360_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, search_ads_360_link]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateSearchAds360LinkRequest): + request = analytics_admin.CreateSearchAds360LinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if search_ads_360_link is not None: + request.search_ads_360_link = search_ads_360_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_search_ads360_link] + + # Certain 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 delete_search_ads360_link(self, + request: Optional[Union[analytics_admin.DeleteSearchAds360LinkRequest, 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 SearchAds360Link on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteSearchAds360LinkRequest, dict]): + The request object. Request message for + DeleteSearchAds360Link RPC. + name (str): + Required. The name of the + SearchAds360Link to delete. Example + format: + properties/1234/SearchAds360Links/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteSearchAds360LinkRequest): + request = analytics_admin.DeleteSearchAds360LinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_search_ads360_link] + + # Certain fields should be provided within 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 update_search_ads360_link(self, + request: Optional[Union[analytics_admin.UpdateSearchAds360LinkRequest, dict]] = None, + *, + search_ads_360_link: Optional[resources.SearchAds360Link] = 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]] = (), + ) -> resources.SearchAds360Link: + r"""Updates a SearchAds360Link on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateSearchAds360LinkRequest, dict]): + The request object. Request message for + UpdateSearchAds360Link RPC. + search_ads_360_link (google.analytics.admin_v1alpha.types.SearchAds360Link): + The SearchAds360Link to update + This corresponds to the ``search_ads_360_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([search_ads_360_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateSearchAds360LinkRequest): + request = analytics_admin.UpdateSearchAds360LinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if search_ads_360_link is not None: + request.search_ads_360_link = search_ads_360_link + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_search_ads360_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("search_ads_360_link.name", request.search_ads_360_link.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_attribution_settings(self, + request: Optional[Union[analytics_admin.GetAttributionSettingsRequest, 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]] = (), + ) -> resources.AttributionSettings: + r"""Lookup for a AttributionSettings singleton. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetAttributionSettingsRequest, dict]): + The request object. Request message for + GetAttributionSettings RPC. + name (str): + Required. The name of the attribution + settings to retrieve. Format: + properties/{property}/attributionSettings + + 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.analytics.admin_v1alpha.types.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAttributionSettingsRequest): + request = analytics_admin.GetAttributionSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_attribution_settings] + + # Certain fields should be provided within 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_attribution_settings(self, + request: Optional[Union[analytics_admin.UpdateAttributionSettingsRequest, dict]] = None, + *, + attribution_settings: Optional[resources.AttributionSettings] = 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]] = (), + ) -> resources.AttributionSettings: + r"""Updates attribution settings on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateAttributionSettingsRequest, dict]): + The request object. Request message for + UpdateAttributionSettings RPC + attribution_settings (google.analytics.admin_v1alpha.types.AttributionSettings): + Required. The attribution settings to update. The + ``name`` field is used to identify the settings to be + updated. + + This corresponds to the ``attribution_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([attribution_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAttributionSettingsRequest): + request = analytics_admin.UpdateAttributionSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if attribution_settings is not None: + request.attribution_settings = attribution_settings + 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_attribution_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("attribution_settings.name", request.attribution_settings.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 run_access_report(self, + request: Optional[Union[analytics_admin.RunAccessReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.RunAccessReportResponse: + r"""Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. + + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. + + Args: + request (Union[google.analytics.admin_v1alpha.types.RunAccessReportRequest, dict]): + The request object. The request for a Data Access Record + Report. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.RunAccessReportResponse: + The customized Data Access Record + Report response. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.RunAccessReportRequest): + request = analytics_admin.RunAccessReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_access_report] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity", request.entity), + )), + ) + + # 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_access_binding(self, + request: Optional[Union[analytics_admin.CreateAccessBindingRequest, dict]] = None, + *, + parent: Optional[str] = None, + access_binding: Optional[resources.AccessBinding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AccessBinding: + r"""Creates an access binding on an account or property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateAccessBindingRequest, dict]): + The request object. Request message for + CreateAccessBinding RPC. + parent (str): + Required. Formats: + + - accounts/{account} + - properties/{property} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + access_binding (google.analytics.admin_v1alpha.types.AccessBinding): + Required. The access binding to + create. + + This corresponds to the ``access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, access_binding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateAccessBindingRequest): + request = analytics_admin.CreateAccessBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if access_binding is not None: + request.access_binding = access_binding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_access_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_access_binding(self, + request: Optional[Union[analytics_admin.GetAccessBindingRequest, 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]] = (), + ) -> resources.AccessBinding: + r"""Gets information about an access binding. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetAccessBindingRequest, dict]): + The request object. Request message for GetAccessBinding + RPC. + name (str): + Required. The name of the access + binding to retrieve. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} + + 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.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAccessBindingRequest): + request = analytics_admin.GetAccessBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_access_binding] + + # Certain fields should be provided within 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_access_binding(self, + request: Optional[Union[analytics_admin.UpdateAccessBindingRequest, dict]] = None, + *, + access_binding: Optional[resources.AccessBinding] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AccessBinding: + r"""Updates an access binding on an account or property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateAccessBindingRequest, dict]): + The request object. Request message for + UpdateAccessBinding RPC. + access_binding (google.analytics.admin_v1alpha.types.AccessBinding): + Required. The access binding to + update. + + This corresponds to the ``access_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AccessBinding: + A binding of a user to a set of + roles. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([access_binding]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAccessBindingRequest): + request = analytics_admin.UpdateAccessBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if access_binding is not None: + request.access_binding = access_binding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_access_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("access_binding.name", request.access_binding.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_access_binding(self, + request: Optional[Union[analytics_admin.DeleteAccessBindingRequest, 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 an access binding on an account or property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteAccessBindingRequest, dict]): + The request object. Request message for + DeleteAccessBinding RPC. + name (str): + Required. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAccessBindingRequest): + request = analytics_admin.DeleteAccessBindingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_access_binding] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_access_bindings(self, + request: Optional[Union[analytics_admin.ListAccessBindingsRequest, 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.ListAccessBindingsPager: + r"""Lists all access bindings on an account or property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListAccessBindingsRequest, dict]): + The request object. Request message for + ListAccessBindings RPC. + parent (str): + Required. Formats: + + - accounts/{account} + - properties/{property} + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAccessBindingsPager: + Response message for + ListAccessBindings RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccessBindingsRequest): + request = analytics_admin.ListAccessBindingsRequest(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_access_bindings] + + # Certain 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.ListAccessBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_create_access_bindings(self, + request: Optional[Union[analytics_admin.BatchCreateAccessBindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.BatchCreateAccessBindingsResponse: + r"""Creates information about multiple access bindings to + an account or property. + + This method is transactional. If any AccessBinding + cannot be created, none of the AccessBindings will be + created. + + Args: + request (Union[google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsRequest, dict]): + The request object. Request message for + BatchCreateAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BatchCreateAccessBindingsResponse: + Response message for + BatchCreateAccessBindings RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchCreateAccessBindingsRequest): + request = analytics_admin.BatchCreateAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_access_bindings] + + # Certain 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 batch_get_access_bindings(self, + request: Optional[Union[analytics_admin.BatchGetAccessBindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.BatchGetAccessBindingsResponse: + r"""Gets information about multiple access bindings to an + account or property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.BatchGetAccessBindingsRequest, dict]): + The request object. Request message for + BatchGetAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BatchGetAccessBindingsResponse: + Response message for + BatchGetAccessBindings RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchGetAccessBindingsRequest): + request = analytics_admin.BatchGetAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_get_access_bindings] + + # Certain 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 batch_update_access_bindings(self, + request: Optional[Union[analytics_admin.BatchUpdateAccessBindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.BatchUpdateAccessBindingsResponse: + r"""Updates information about multiple access bindings to + an account or property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsRequest, dict]): + The request object. Request message for + BatchUpdateAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BatchUpdateAccessBindingsResponse: + Response message for + BatchUpdateAccessBindings RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchUpdateAccessBindingsRequest): + request = analytics_admin.BatchUpdateAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_access_bindings] + + # Certain 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 batch_delete_access_bindings(self, + request: Optional[Union[analytics_admin.BatchDeleteAccessBindingsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes information about multiple users' links to an + account or property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.BatchDeleteAccessBindingsRequest, dict]): + The request object. Request message for + BatchDeleteAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.BatchDeleteAccessBindingsRequest): + request = analytics_admin.BatchDeleteAccessBindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_access_bindings] + + # Certain 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_expanded_data_set(self, + request: Optional[Union[analytics_admin.GetExpandedDataSetRequest, 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]] = (), + ) -> expanded_data_set.ExpandedDataSet: + r"""Lookup for a single ExpandedDataSet. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetExpandedDataSetRequest, dict]): + The request object. Request message for + GetExpandedDataSet RPC. + name (str): + Required. The name of the + ExpandedDataSet to get. Example format: + properties/1234/expandedDataSets/5678 + + 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.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetExpandedDataSetRequest): + request = analytics_admin.GetExpandedDataSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_expanded_data_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_expanded_data_sets(self, + request: Optional[Union[analytics_admin.ListExpandedDataSetsRequest, 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.ListExpandedDataSetsPager: + r"""Lists ExpandedDataSets on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListExpandedDataSetsRequest, dict]): + The request object. Request message for + ListExpandedDataSets RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListExpandedDataSetsPager: + Response message for + ListExpandedDataSets RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListExpandedDataSetsRequest): + request = analytics_admin.ListExpandedDataSetsRequest(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_expanded_data_sets] + + # Certain 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.ListExpandedDataSetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_expanded_data_set(self, + request: Optional[Union[analytics_admin.CreateExpandedDataSetRequest, dict]] = None, + *, + parent: Optional[str] = None, + expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Creates a ExpandedDataSet. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateExpandedDataSetRequest, dict]): + The request object. Request message for + CreateExpandedDataSet RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + expanded_data_set (google.analytics.admin_v1alpha.types.ExpandedDataSet): + Required. The ExpandedDataSet to + create. + + This corresponds to the ``expanded_data_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, expanded_data_set]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateExpandedDataSetRequest): + request = analytics_admin.CreateExpandedDataSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if expanded_data_set is not None: + request.expanded_data_set = expanded_data_set + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_expanded_data_set] + + # Certain 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_expanded_data_set(self, + request: Optional[Union[analytics_admin.UpdateExpandedDataSetRequest, dict]] = None, + *, + expanded_data_set: Optional[gaa_expanded_data_set.ExpandedDataSet] = 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]] = (), + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Updates a ExpandedDataSet on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateExpandedDataSetRequest, dict]): + The request object. Request message for + UpdateExpandedDataSet RPC. + expanded_data_set (google.analytics.admin_v1alpha.types.ExpandedDataSet): + Required. The ExpandedDataSet to update. The resource's + ``name`` field is used to identify the ExpandedDataSet + to be updated. + + This corresponds to the ``expanded_data_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([expanded_data_set, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateExpandedDataSetRequest): + request = analytics_admin.UpdateExpandedDataSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if expanded_data_set is not None: + request.expanded_data_set = expanded_data_set + 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_expanded_data_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("expanded_data_set.name", request.expanded_data_set.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_expanded_data_set(self, + request: Optional[Union[analytics_admin.DeleteExpandedDataSetRequest, 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 ExpandedDataSet on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteExpandedDataSetRequest, dict]): + The request object. Request message for + DeleteExpandedDataSet RPC. + name (str): + Required. Example format: + properties/1234/expandedDataSets/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteExpandedDataSetRequest): + request = analytics_admin.DeleteExpandedDataSetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_expanded_data_set] + + # Certain fields should be provided within 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_channel_group(self, + request: Optional[Union[analytics_admin.GetChannelGroupRequest, 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]] = (), + ) -> channel_group.ChannelGroup: + r"""Lookup for a single ChannelGroup. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetChannelGroupRequest, dict]): + The request object. Request message for GetChannelGroup + RPC. + name (str): + Required. The ChannelGroup to get. + Example format: + properties/1234/channelGroups/5678 + + 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.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetChannelGroupRequest): + request = analytics_admin.GetChannelGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_channel_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_channel_groups(self, + request: Optional[Union[analytics_admin.ListChannelGroupsRequest, 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.ListChannelGroupsPager: + r"""Lists ChannelGroups on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListChannelGroupsRequest, dict]): + The request object. Request message for ListChannelGroups + RPC. + parent (str): + Required. The property for which to + list ChannelGroups. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListChannelGroupsPager: + Response message for + ListChannelGroups RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListChannelGroupsRequest): + request = analytics_admin.ListChannelGroupsRequest(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_channel_groups] + + # Certain 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.ListChannelGroupsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_channel_group(self, + request: Optional[Union[analytics_admin.CreateChannelGroupRequest, dict]] = None, + *, + parent: Optional[str] = None, + channel_group: Optional[gaa_channel_group.ChannelGroup] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gaa_channel_group.ChannelGroup: + r"""Creates a ChannelGroup. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateChannelGroupRequest, dict]): + The request object. Request message for + CreateChannelGroup RPC. + parent (str): + Required. The property for which to + create a ChannelGroup. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + channel_group (google.analytics.admin_v1alpha.types.ChannelGroup): + Required. The ChannelGroup to create. + This corresponds to the ``channel_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, channel_group]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateChannelGroupRequest): + request = analytics_admin.CreateChannelGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if channel_group is not None: + request.channel_group = channel_group + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_channel_group] + + # Certain 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_channel_group(self, + request: Optional[Union[analytics_admin.UpdateChannelGroupRequest, dict]] = None, + *, + channel_group: Optional[gaa_channel_group.ChannelGroup] = 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]] = (), + ) -> gaa_channel_group.ChannelGroup: + r"""Updates a ChannelGroup. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateChannelGroupRequest, dict]): + The request object. Request message for + UpdateChannelGroup RPC. + channel_group (google.analytics.admin_v1alpha.types.ChannelGroup): + Required. The ChannelGroup to update. The resource's + ``name`` field is used to identify the ChannelGroup to + be updated. + + This corresponds to the ``channel_group`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ChannelGroup: + A resource message representing a + Channel Group. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([channel_group, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateChannelGroupRequest): + request = analytics_admin.UpdateChannelGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if channel_group is not None: + request.channel_group = channel_group + 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_channel_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("channel_group.name", request.channel_group.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_channel_group(self, + request: Optional[Union[analytics_admin.DeleteChannelGroupRequest, 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 ChannelGroup on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteChannelGroupRequest, dict]): + The request object. Request message for + DeleteChannelGroup RPC. + name (str): + Required. The ChannelGroup to delete. + Example format: + properties/1234/channelGroups/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteChannelGroupRequest): + request = analytics_admin.DeleteChannelGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_channel_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def set_automated_ga4_configuration_opt_out(self, + request: Optional[Union[analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse: + r"""Sets the opt out status for the automated GA4 setup + process for a UA property. + Note: this has no effect on GA4 property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutRequest, dict]): + The request object. Request for setting the opt out + status for the automated GA4 setup + process. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SetAutomatedGa4ConfigurationOptOutResponse: + Response message for setting the opt + out status for the automated GA4 setup + process. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest): + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_automated_ga4_configuration_opt_out] + + # 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 fetch_automated_ga4_configuration_opt_out(self, + request: Optional[Union[analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse: + r"""Fetches the opt out status for the automated GA4 + setup process for a UA property. + Note: this has no effect on GA4 property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutRequest, dict]): + The request object. Request for fetching the opt out + status for the automated GA4 setup + process. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.FetchAutomatedGa4ConfigurationOptOutResponse: + Response message for fetching the opt + out status for the automated GA4 setup + process. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest): + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_automated_ga4_configuration_opt_out] + + # 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_big_query_link(self, + request: Optional[Union[analytics_admin.CreateBigQueryLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + bigquery_link: Optional[resources.BigQueryLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.BigQueryLink: + r"""Creates a BigQueryLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateBigQueryLinkRequest, dict]): + The request object. Request message for + CreateBigQueryLink RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + bigquery_link (google.analytics.admin_v1alpha.types.BigQueryLink): + Required. The BigQueryLink to create. + This corresponds to the ``bigquery_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, bigquery_link]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateBigQueryLinkRequest): + request = analytics_admin.CreateBigQueryLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if bigquery_link is not None: + request.bigquery_link = bigquery_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_big_query_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_big_query_link(self, + request: Optional[Union[analytics_admin.GetBigQueryLinkRequest, 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]] = (), + ) -> resources.BigQueryLink: + r"""Lookup for a single BigQuery Link. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetBigQueryLinkRequest, dict]): + The request object. Request message for GetBigQueryLink + RPC. + name (str): + Required. The name of the BigQuery link to lookup. + Format: + properties/{property_id}/bigQueryLinks/{bigquery_link_id} + Example: properties/123/bigQueryLinks/456 + + 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.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetBigQueryLinkRequest): + request = analytics_admin.GetBigQueryLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_big_query_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_big_query_links(self, + request: Optional[Union[analytics_admin.ListBigQueryLinksRequest, 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.ListBigQueryLinksPager: + r"""Lists BigQuery Links on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListBigQueryLinksRequest, dict]): + The request object. Request message for ListBigQueryLinks + RPC. + parent (str): + Required. The name of the property to list BigQuery + links under. Format: properties/{property_id} Example: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListBigQueryLinksPager: + Response message for + ListBigQueryLinks RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListBigQueryLinksRequest): + request = analytics_admin.ListBigQueryLinksRequest(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_big_query_links] + + # Certain 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.ListBigQueryLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_big_query_link(self, + request: Optional[Union[analytics_admin.DeleteBigQueryLinkRequest, 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 BigQueryLink on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteBigQueryLinkRequest, dict]): + The request object. Request message for + DeleteBigQueryLink RPC. + name (str): + Required. The BigQueryLink to delete. + Example format: + properties/1234/bigQueryLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteBigQueryLinkRequest): + request = analytics_admin.DeleteBigQueryLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_big_query_link] + + # Certain fields should be provided within 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 update_big_query_link(self, + request: Optional[Union[analytics_admin.UpdateBigQueryLinkRequest, dict]] = None, + *, + bigquery_link: Optional[resources.BigQueryLink] = 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]] = (), + ) -> resources.BigQueryLink: + r"""Updates a BigQueryLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateBigQueryLinkRequest, dict]): + The request object. Request message for + UpdateBigQueryLink RPC. + bigquery_link (google.analytics.admin_v1alpha.types.BigQueryLink): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``bigquery_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([bigquery_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateBigQueryLinkRequest): + request = analytics_admin.UpdateBigQueryLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if bigquery_link is not None: + request.bigquery_link = bigquery_link + 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_big_query_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("bigquery_link.name", request.bigquery_link.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_enhanced_measurement_settings(self, + request: Optional[Union[analytics_admin.GetEnhancedMeasurementSettingsRequest, 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]] = (), + ) -> resources.EnhancedMeasurementSettings: + r"""Returns the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetEnhancedMeasurementSettingsRequest, dict]): + The request object. Request message for + GetEnhancedMeasurementSettings RPC. + name (str): + Required. The name of the settings to lookup. Format: + properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings + Example: + "properties/1000/dataStreams/2000/enhancedMeasurementSettings" + + 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.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetEnhancedMeasurementSettingsRequest): + request = analytics_admin.GetEnhancedMeasurementSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_enhanced_measurement_settings] + + # Certain fields should be provided within 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_enhanced_measurement_settings(self, + request: Optional[Union[analytics_admin.UpdateEnhancedMeasurementSettingsRequest, dict]] = None, + *, + enhanced_measurement_settings: Optional[resources.EnhancedMeasurementSettings] = 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]] = (), + ) -> resources.EnhancedMeasurementSettings: + r"""Updates the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateEnhancedMeasurementSettingsRequest, dict]): + The request object. Request message for + UpdateEnhancedMeasurementSettings RPC. + enhanced_measurement_settings (google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``enhanced_measurement_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([enhanced_measurement_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateEnhancedMeasurementSettingsRequest): + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if enhanced_measurement_settings is not None: + request.enhanced_measurement_settings = enhanced_measurement_settings + 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_enhanced_measurement_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("enhanced_measurement_settings.name", request.enhanced_measurement_settings.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_connected_site_tag(self, + request: Optional[Union[analytics_admin.CreateConnectedSiteTagRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.CreateConnectedSiteTagResponse: + r"""Creates a connected site tag for a Universal + Analytics property. You can create a maximum of 20 + connected site tags per property. Note: This API cannot + be used on GA4 properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateConnectedSiteTagRequest, dict]): + The request object. Request message for + CreateConnectedSiteTag RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CreateConnectedSiteTagResponse: + Response message for + CreateConnectedSiteTag RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateConnectedSiteTagRequest): + request = analytics_admin.CreateConnectedSiteTagRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_connected_site_tag] + + # 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_connected_site_tag(self, + request: Optional[Union[analytics_admin.DeleteConnectedSiteTagRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a connected site tag for a Universal + Analytics property. Note: this has no effect on GA4 + properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteConnectedSiteTagRequest, dict]): + The request object. Request message for + DeleteConnectedSiteTag RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteConnectedSiteTagRequest): + request = analytics_admin.DeleteConnectedSiteTagRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_connected_site_tag] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_connected_site_tags(self, + request: Optional[Union[analytics_admin.ListConnectedSiteTagsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ListConnectedSiteTagsResponse: + r"""Lists the connected site tags for a Universal + Analytics property. A maximum of 20 connected site tags + will be returned. Note: this has no effect on GA4 + property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListConnectedSiteTagsRequest, dict]): + The request object. Request message for + ListConnectedSiteTags RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ListConnectedSiteTagsResponse: + Response message for + ListConnectedSiteTags RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListConnectedSiteTagsRequest): + request = analytics_admin.ListConnectedSiteTagsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_connected_site_tags] + + # 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 fetch_connected_ga4_property(self, + request: Optional[Union[analytics_admin.FetchConnectedGa4PropertyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.FetchConnectedGa4PropertyResponse: + r"""Given a specified UA property, looks up the GA4 + property connected to it. Note: this cannot be used with + GA4 properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyRequest, dict]): + The request object. Request for looking up GA4 property + connected to a UA property. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.FetchConnectedGa4PropertyResponse: + Response for looking up GA4 property + connected to a UA property. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.FetchConnectedGa4PropertyRequest): + request = analytics_admin.FetchConnectedGa4PropertyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_connected_ga4_property] + + # 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_ad_sense_link(self, + request: Optional[Union[analytics_admin.GetAdSenseLinkRequest, 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]] = (), + ) -> resources.AdSenseLink: + r"""Looks up a single AdSenseLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetAdSenseLinkRequest, dict]): + The request object. Request message to be passed to + GetAdSenseLink method. + name (str): + Required. Unique identifier for the + AdSense Link requested. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: + properties/1234/adSenseLinks/5678 + + 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.analytics.admin_v1alpha.types.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAdSenseLinkRequest): + request = analytics_admin.GetAdSenseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_ad_sense_link] + + # Certain fields should be provided within 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_ad_sense_link(self, + request: Optional[Union[analytics_admin.CreateAdSenseLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + adsense_link: Optional[resources.AdSenseLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.AdSenseLink: + r"""Creates an AdSenseLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateAdSenseLinkRequest, dict]): + The request object. Request message to be passed to + CreateAdSenseLink method. + parent (str): + Required. The property for which to + create an AdSense Link. Format: + properties/{propertyId} Example: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + adsense_link (google.analytics.admin_v1alpha.types.AdSenseLink): + Required. The AdSense Link to create + This corresponds to the ``adsense_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, adsense_link]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateAdSenseLinkRequest): + request = analytics_admin.CreateAdSenseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if adsense_link is not None: + request.adsense_link = adsense_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_ad_sense_link] + + # Certain 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 delete_ad_sense_link(self, + request: Optional[Union[analytics_admin.DeleteAdSenseLinkRequest, 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 an AdSenseLink. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteAdSenseLinkRequest, dict]): + The request object. Request message to be passed to + DeleteAdSenseLink method. + name (str): + Required. Unique identifier for the + AdSense Link to be deleted. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: + properties/1234/adSenseLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAdSenseLinkRequest): + request = analytics_admin.DeleteAdSenseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_ad_sense_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_ad_sense_links(self, + request: Optional[Union[analytics_admin.ListAdSenseLinksRequest, 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.ListAdSenseLinksPager: + r"""Lists AdSenseLinks on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListAdSenseLinksRequest, dict]): + The request object. Request message to be passed to + ListAdSenseLinks method. + parent (str): + Required. Resource name of the parent + property. Format: + properties/{propertyId} + Example: properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListAdSenseLinksPager: + Response message for ListAdSenseLinks + method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAdSenseLinksRequest): + request = analytics_admin.ListAdSenseLinksRequest(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_ad_sense_links] + + # Certain 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.ListAdSenseLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_event_create_rule(self, + request: Optional[Union[analytics_admin.GetEventCreateRuleRequest, 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]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Lookup for a single EventCreateRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetEventCreateRuleRequest, dict]): + The request object. Request message for + GetEventCreateRule RPC. + name (str): + Required. The name of the + EventCreateRule to get. Example format: + properties/123/dataStreams/456/eventCreateRules/789 + + 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.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetEventCreateRuleRequest): + request = analytics_admin.GetEventCreateRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_event_create_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_event_create_rules(self, + request: Optional[Union[analytics_admin.ListEventCreateRulesRequest, 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.ListEventCreateRulesPager: + r"""Lists EventCreateRules on a web data stream. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListEventCreateRulesRequest, dict]): + The request object. Request message for + ListEventCreateRules RPC. + parent (str): + Required. Example format: + properties/123/dataStreams/456 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventCreateRulesPager: + Response message for + ListEventCreateRules RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListEventCreateRulesRequest): + request = analytics_admin.ListEventCreateRulesRequest(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_event_create_rules] + + # Certain 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.ListEventCreateRulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_event_create_rule(self, + request: Optional[Union[analytics_admin.CreateEventCreateRuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + event_create_rule: Optional[event_create_and_edit.EventCreateRule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Creates an EventCreateRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateEventCreateRuleRequest, dict]): + The request object. Request message for + CreateEventCreateRule RPC. + parent (str): + Required. Example format: + properties/123/dataStreams/456 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_create_rule (google.analytics.admin_v1alpha.types.EventCreateRule): + Required. The EventCreateRule to + create. + + This corresponds to the ``event_create_rule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event_create_rule]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateEventCreateRuleRequest): + request = analytics_admin.CreateEventCreateRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event_create_rule is not None: + request.event_create_rule = event_create_rule + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_event_create_rule] + + # Certain 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_event_create_rule(self, + request: Optional[Union[analytics_admin.UpdateEventCreateRuleRequest, dict]] = None, + *, + event_create_rule: Optional[event_create_and_edit.EventCreateRule] = 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]] = (), + ) -> event_create_and_edit.EventCreateRule: + r"""Updates an EventCreateRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateEventCreateRuleRequest, dict]): + The request object. Request message for + UpdateEventCreateRule RPC. + event_create_rule (google.analytics.admin_v1alpha.types.EventCreateRule): + Required. The EventCreateRule to update. The resource's + ``name`` field is used to identify the EventCreateRule + to be updated. + + This corresponds to the ``event_create_rule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event_create_rule, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateEventCreateRuleRequest): + request = analytics_admin.UpdateEventCreateRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event_create_rule is not None: + request.event_create_rule = event_create_rule + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_event_create_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event_create_rule.name", request.event_create_rule.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_event_create_rule(self, + request: Optional[Union[analytics_admin.DeleteEventCreateRuleRequest, 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 an EventCreateRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteEventCreateRuleRequest, dict]): + The request object. Request message for + DeleteEventCreateRule RPC. + name (str): + Required. Example format: + + properties/123/dataStreams/456/eventCreateRules/789 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteEventCreateRuleRequest): + request = analytics_admin.DeleteEventCreateRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_event_create_rule] + + # Certain fields should be provided within 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_event_edit_rule(self, + request: Optional[Union[analytics_admin.GetEventEditRuleRequest, 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]] = (), + ) -> event_create_and_edit.EventEditRule: + r"""Lookup for a single EventEditRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetEventEditRuleRequest, dict]): + The request object. Request message for GetEventEditRule + RPC. + name (str): + Required. The name of the + EventEditRule to get. Example format: + properties/123/dataStreams/456/eventEditRules/789 + + 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.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetEventEditRuleRequest): + request = analytics_admin.GetEventEditRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_event_edit_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_event_edit_rules(self, + request: Optional[Union[analytics_admin.ListEventEditRulesRequest, 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.ListEventEditRulesPager: + r"""Lists EventEditRules on a web data stream. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListEventEditRulesRequest, dict]): + The request object. Request message for + ListEventEditRules RPC. + parent (str): + Required. Example format: + properties/123/dataStreams/456 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListEventEditRulesPager: + Response message for + ListEventEditRules RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListEventEditRulesRequest): + request = analytics_admin.ListEventEditRulesRequest(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_event_edit_rules] + + # Certain 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.ListEventEditRulesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_event_edit_rule(self, + request: Optional[Union[analytics_admin.CreateEventEditRuleRequest, dict]] = None, + *, + parent: Optional[str] = None, + event_edit_rule: Optional[event_create_and_edit.EventEditRule] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> event_create_and_edit.EventEditRule: + r"""Creates an EventEditRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateEventEditRuleRequest, dict]): + The request object. Request message for + CreateEventEditRule RPC. + parent (str): + Required. Example format: + properties/123/dataStreams/456 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + event_edit_rule (google.analytics.admin_v1alpha.types.EventEditRule): + Required. The EventEditRule to + create. + + This corresponds to the ``event_edit_rule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, event_edit_rule]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateEventEditRuleRequest): + request = analytics_admin.CreateEventEditRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if event_edit_rule is not None: + request.event_edit_rule = event_edit_rule + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_event_edit_rule] + + # Certain 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_event_edit_rule(self, + request: Optional[Union[analytics_admin.UpdateEventEditRuleRequest, dict]] = None, + *, + event_edit_rule: Optional[event_create_and_edit.EventEditRule] = 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]] = (), + ) -> event_create_and_edit.EventEditRule: + r"""Updates an EventEditRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateEventEditRuleRequest, dict]): + The request object. Request message for + UpdateEventEditRule RPC. + event_edit_rule (google.analytics.admin_v1alpha.types.EventEditRule): + Required. The EventEditRule to update. The resource's + ``name`` field is used to identify the EventEditRule to + be updated. + + This corresponds to the ``event_edit_rule`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([event_edit_rule, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateEventEditRuleRequest): + request = analytics_admin.UpdateEventEditRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if event_edit_rule is not None: + request.event_edit_rule = event_edit_rule + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_event_edit_rule] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("event_edit_rule.name", request.event_edit_rule.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_event_edit_rule(self, + request: Optional[Union[analytics_admin.DeleteEventEditRuleRequest, 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 an EventEditRule. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteEventEditRuleRequest, dict]): + The request object. Request message for + DeleteEventEditRule RPC. + name (str): + Required. Example format: + properties/123/dataStreams/456/eventEditRules/789 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteEventEditRuleRequest): + request = analytics_admin.DeleteEventEditRuleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_event_edit_rule] + + # Certain fields should be provided within 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 reorder_event_edit_rules(self, + request: Optional[Union[analytics_admin.ReorderEventEditRulesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Changes the processing order of event edit rules on + the specified stream. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ReorderEventEditRulesRequest, dict]): + The request object. Request message for + ReorderEventEditRules RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ReorderEventEditRulesRequest): + request = analytics_admin.ReorderEventEditRulesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.reorder_event_edit_rules] + + # Certain 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. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_data_redaction_settings(self, + request: Optional[Union[analytics_admin.UpdateDataRedactionSettingsRequest, dict]] = None, + *, + data_redaction_settings: Optional[resources.DataRedactionSettings] = 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]] = (), + ) -> resources.DataRedactionSettings: + r"""Updates a DataRedactionSettings on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateDataRedactionSettingsRequest, dict]): + The request object. Request message for + UpdateDataRedactionSettings RPC. + data_redaction_settings (google.analytics.admin_v1alpha.types.DataRedactionSettings): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``data_redaction_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.DataRedactionSettings: + Settings for client-side data + redaction. Singleton resource under a + Web Stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_redaction_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataRedactionSettingsRequest): + request = analytics_admin.UpdateDataRedactionSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_redaction_settings is not None: + request.data_redaction_settings = data_redaction_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_data_redaction_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_redaction_settings.name", request.data_redaction_settings.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_data_redaction_settings(self, + request: Optional[Union[analytics_admin.GetDataRedactionSettingsRequest, 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]] = (), + ) -> resources.DataRedactionSettings: + r"""Lookup for a single DataRedactionSettings. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetDataRedactionSettingsRequest, dict]): + The request object. Request message for + GetDataRedactionSettings RPC. + name (str): + Required. The name of the settings to lookup. Format: + properties/{property}/dataStreams/{data_stream}/dataRedactionSettings + Example: + "properties/1000/dataStreams/2000/dataRedactionSettings" + + 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.analytics.admin_v1alpha.types.DataRedactionSettings: + Settings for client-side data + redaction. Singleton resource under a + Web Stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataRedactionSettingsRequest): + request = analytics_admin.GetDataRedactionSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_data_redaction_settings] + + # Certain fields should be provided within 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_calculated_metric(self, + request: Optional[Union[analytics_admin.GetCalculatedMetricRequest, 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]] = (), + ) -> resources.CalculatedMetric: + r"""Lookup for a single CalculatedMetric. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetCalculatedMetricRequest, dict]): + The request object. Request message for + GetCalculatedMetric RPC. + name (str): + Required. The name of the CalculatedMetric to get. + Format: + properties/{property_id}/calculatedMetrics/{calculated_metric_id} + Example: properties/1234/calculatedMetrics/Metric01 + + 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.analytics.admin_v1alpha.types.CalculatedMetric: + A definition for a calculated metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCalculatedMetricRequest): + request = analytics_admin.GetCalculatedMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_calculated_metric] + + # Certain fields should be provided within 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_calculated_metric(self, + request: Optional[Union[analytics_admin.CreateCalculatedMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + calculated_metric: Optional[resources.CalculatedMetric] = None, + calculated_metric_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CalculatedMetric: + r"""Creates a CalculatedMetric. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateCalculatedMetricRequest, dict]): + The request object. Request message for + CreateCalculatedMetric RPC. + parent (str): + Required. Format: properties/{property_id} Example: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + calculated_metric (google.analytics.admin_v1alpha.types.CalculatedMetric): + Required. The CalculatedMetric to + create. + + This corresponds to the ``calculated_metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + calculated_metric_id (str): + Required. The ID to use for the calculated metric which + will become the final component of the calculated + metric's resource name. + + This value should be 1-80 characters and valid + characters are /[a-zA-Z0-9_]/, no spaces allowed. + calculated_metric_id must be unique between all + calculated metrics under a property. The + calculated_metric_id is used when referencing this + calculated metric from external APIs, for example, + "calcMetric:{calculated_metric_id}". + + This corresponds to the ``calculated_metric_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.analytics.admin_v1alpha.types.CalculatedMetric: + A definition for a calculated metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, calculated_metric, calculated_metric_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCalculatedMetricRequest): + request = analytics_admin.CreateCalculatedMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if calculated_metric is not None: + request.calculated_metric = calculated_metric + if calculated_metric_id is not None: + request.calculated_metric_id = calculated_metric_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_calculated_metric] + + # Certain 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_calculated_metrics(self, + request: Optional[Union[analytics_admin.ListCalculatedMetricsRequest, 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.ListCalculatedMetricsPager: + r"""Lists CalculatedMetrics on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListCalculatedMetricsRequest, dict]): + The request object. Request message for + ListCalculatedMetrics RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListCalculatedMetricsPager: + Response message for + ListCalculatedMetrics RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCalculatedMetricsRequest): + request = analytics_admin.ListCalculatedMetricsRequest(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_calculated_metrics] + + # Certain 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.ListCalculatedMetricsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_calculated_metric(self, + request: Optional[Union[analytics_admin.UpdateCalculatedMetricRequest, dict]] = None, + *, + calculated_metric: Optional[resources.CalculatedMetric] = 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]] = (), + ) -> resources.CalculatedMetric: + r"""Updates a CalculatedMetric on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateCalculatedMetricRequest, dict]): + The request object. Request message for + UpdateCalculatedMetric RPC. + calculated_metric (google.analytics.admin_v1alpha.types.CalculatedMetric): + Required. The CalculatedMetric to + update + + This corresponds to the ``calculated_metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CalculatedMetric: + A definition for a calculated metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([calculated_metric, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCalculatedMetricRequest): + request = analytics_admin.UpdateCalculatedMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if calculated_metric is not None: + request.calculated_metric = calculated_metric + 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_calculated_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("calculated_metric.name", request.calculated_metric.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_calculated_metric(self, + request: Optional[Union[analytics_admin.DeleteCalculatedMetricRequest, 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 CalculatedMetric on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteCalculatedMetricRequest, dict]): + The request object. Request message for + DeleteCalculatedMetric RPC. + name (str): + Required. The name of the CalculatedMetric to delete. + Format: + properties/{property_id}/calculatedMetrics/{calculated_metric_id} + Example: properties/1234/calculatedMetrics/Metric01 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteCalculatedMetricRequest): + request = analytics_admin.DeleteCalculatedMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_calculated_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_rollup_property(self, + request: Optional[Union[analytics_admin.CreateRollupPropertyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.CreateRollupPropertyResponse: + r"""Create a roll-up property and all roll-up property + source links. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateRollupPropertyRequest, dict]): + The request object. Request message for + CreateRollupProperty RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.CreateRollupPropertyResponse: + Response message for + CreateRollupProperty RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateRollupPropertyRequest): + request = analytics_admin.CreateRollupPropertyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_rollup_property] + + # 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_rollup_property_source_link(self, + request: Optional[Union[analytics_admin.GetRollupPropertySourceLinkRequest, 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]] = (), + ) -> resources.RollupPropertySourceLink: + r"""Lookup for a single roll-up property source Link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetRollupPropertySourceLinkRequest, dict]): + The request object. Request message for + GetRollupPropertySourceLink RPC. + name (str): + Required. The name of the roll-up property source link + to lookup. Format: + properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} + Example: properties/123/rollupPropertySourceLinks/456 + + 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.analytics.admin_v1alpha.types.RollupPropertySourceLink: + A link that references a source + property under the parent rollup + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetRollupPropertySourceLinkRequest): + request = analytics_admin.GetRollupPropertySourceLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_rollup_property_source_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_rollup_property_source_links(self, + request: Optional[Union[analytics_admin.ListRollupPropertySourceLinksRequest, 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.ListRollupPropertySourceLinksPager: + r"""Lists roll-up property source Links on a property. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksRequest, dict]): + The request object. Request message for + ListRollupPropertySourceLinks RPC. + parent (str): + Required. The name of the roll-up property to list + roll-up property source links under. Format: + properties/{property_id} Example: properties/1234 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListRollupPropertySourceLinksPager: + Response message for + ListRollupPropertySourceLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListRollupPropertySourceLinksRequest): + request = analytics_admin.ListRollupPropertySourceLinksRequest(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_rollup_property_source_links] + + # Certain 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.ListRollupPropertySourceLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_rollup_property_source_link(self, + request: Optional[Union[analytics_admin.CreateRollupPropertySourceLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + rollup_property_source_link: Optional[resources.RollupPropertySourceLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.RollupPropertySourceLink: + r"""Creates a roll-up property source link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateRollupPropertySourceLinkRequest, dict]): + The request object. Request message for + CreateRollupPropertySourceLink RPC. + parent (str): + Required. Format: properties/{property_id} Example: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollup_property_source_link (google.analytics.admin_v1alpha.types.RollupPropertySourceLink): + Required. The roll-up property source + link to create. + + This corresponds to the ``rollup_property_source_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.RollupPropertySourceLink: + A link that references a source + property under the parent rollup + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, rollup_property_source_link]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateRollupPropertySourceLinkRequest): + request = analytics_admin.CreateRollupPropertySourceLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if rollup_property_source_link is not None: + request.rollup_property_source_link = rollup_property_source_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_rollup_property_source_link] + + # Certain 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 delete_rollup_property_source_link(self, + request: Optional[Union[analytics_admin.DeleteRollupPropertySourceLinkRequest, 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 roll-up property source link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteRollupPropertySourceLinkRequest, dict]): + The request object. Request message for + DeleteRollupPropertySourceLink RPC. + name (str): + Required. Format: + properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} + Example: properties/1234/rollupPropertySourceLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteRollupPropertySourceLinkRequest): + request = analytics_admin.DeleteRollupPropertySourceLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_rollup_property_source_link] + + # Certain fields should be provided within 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 provision_subproperty(self, + request: Optional[Union[analytics_admin.ProvisionSubpropertyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ProvisionSubpropertyResponse: + r"""Create a subproperty and a subproperty event filter + that applies to the created subproperty. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ProvisionSubpropertyRequest, dict]): + The request object. Request message for CreateSubproperty + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.ProvisionSubpropertyResponse: + Response message for + ProvisionSubproperty RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ProvisionSubpropertyRequest): + request = analytics_admin.ProvisionSubpropertyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.provision_subproperty] + + # 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_subproperty_event_filter(self, + request: Optional[Union[analytics_admin.CreateSubpropertyEventFilterRequest, dict]] = None, + *, + parent: Optional[str] = None, + subproperty_event_filter: Optional[gaa_subproperty_event_filter.SubpropertyEventFilter] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gaa_subproperty_event_filter.SubpropertyEventFilter: + r"""Creates a subproperty Event Filter. + + Args: + request (Union[google.analytics.admin_v1alpha.types.CreateSubpropertyEventFilterRequest, dict]): + The request object. Request message for + CreateSubpropertyEventFilter RPC. + parent (str): + Required. The ordinary property for which to create a + subproperty event filter. Format: properties/property_id + Example: properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subproperty_event_filter (google.analytics.admin_v1alpha.types.SubpropertyEventFilter): + Required. The subproperty event + filter to create. + + This corresponds to the ``subproperty_event_filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SubpropertyEventFilter: + A resource message representing a GA4 + Subproperty event filter. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, subproperty_event_filter]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateSubpropertyEventFilterRequest): + request = analytics_admin.CreateSubpropertyEventFilterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if subproperty_event_filter is not None: + request.subproperty_event_filter = subproperty_event_filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_subproperty_event_filter] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_subproperty_event_filter(self, + request: Optional[Union[analytics_admin.GetSubpropertyEventFilterRequest, 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]] = (), + ) -> subproperty_event_filter.SubpropertyEventFilter: + r"""Lookup for a single subproperty Event Filter. + + Args: + request (Union[google.analytics.admin_v1alpha.types.GetSubpropertyEventFilterRequest, dict]): + The request object. Request message for + GetSubpropertyEventFilter RPC. + name (str): + Required. Resource name of the subproperty event filter + to lookup. Format: + properties/property_id/subpropertyEventFilters/subproperty_event_filter + Example: properties/123/subpropertyEventFilters/456 + + 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.analytics.admin_v1alpha.types.SubpropertyEventFilter: + A resource message representing a GA4 + Subproperty event filter. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetSubpropertyEventFilterRequest): + request = analytics_admin.GetSubpropertyEventFilterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_subproperty_event_filter] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_subproperty_event_filters(self, + request: Optional[Union[analytics_admin.ListSubpropertyEventFiltersRequest, 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.ListSubpropertyEventFiltersPager: + r"""List all subproperty Event Filters on a property. + + Args: + request (Union[google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersRequest, dict]): + The request object. Request message for + ListSubpropertyEventFilters RPC. + parent (str): + Required. Resource name of the ordinary property. + Format: properties/property_id Example: properties/123 + + 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.analytics.admin_v1alpha.services.analytics_admin_service.pagers.ListSubpropertyEventFiltersPager: + Response message for + ListSubpropertyEventFilter RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListSubpropertyEventFiltersRequest): + request = analytics_admin.ListSubpropertyEventFiltersRequest(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_subproperty_event_filters] + + # Certain 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.ListSubpropertyEventFiltersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_subproperty_event_filter(self, + request: Optional[Union[analytics_admin.UpdateSubpropertyEventFilterRequest, dict]] = None, + *, + subproperty_event_filter: Optional[gaa_subproperty_event_filter.SubpropertyEventFilter] = 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]] = (), + ) -> gaa_subproperty_event_filter.SubpropertyEventFilter: + r"""Updates a subproperty Event Filter. + + Args: + request (Union[google.analytics.admin_v1alpha.types.UpdateSubpropertyEventFilterRequest, dict]): + The request object. Request message for + UpdateSubpropertyEventFilter RPC. + subproperty_event_filter (google.analytics.admin_v1alpha.types.SubpropertyEventFilter): + Required. The subproperty event + filter to update. + + This corresponds to the ``subproperty_event_filter`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field names must + be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "*" to match + all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1alpha.types.SubpropertyEventFilter: + A resource message representing a GA4 + Subproperty event filter. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([subproperty_event_filter, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateSubpropertyEventFilterRequest): + request = analytics_admin.UpdateSubpropertyEventFilterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subproperty_event_filter is not None: + request.subproperty_event_filter = subproperty_event_filter + 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_subproperty_event_filter] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("subproperty_event_filter.name", request.subproperty_event_filter.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_subproperty_event_filter(self, + request: Optional[Union[analytics_admin.DeleteSubpropertyEventFilterRequest, 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 subproperty event filter. + + Args: + request (Union[google.analytics.admin_v1alpha.types.DeleteSubpropertyEventFilterRequest, dict]): + The request object. Request message for + DeleteSubpropertyEventFilter RPC. + name (str): + Required. Resource name of the subproperty event filter + to delete. Format: + properties/property_id/subpropertyEventFilters/subproperty_event_filter + Example: properties/123/subpropertyEventFilters/456 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteSubpropertyEventFilterRequest): + request = analytics_admin.DeleteSubpropertyEventFilterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_subproperty_event_filter] + + # Certain fields should be provided within 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 __enter__(self) -> "AnalyticsAdminServiceClient": + 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__ = ( + "AnalyticsAdminServiceClient", +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/pagers.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/pagers.py new file mode 100644 index 000000000000..5026576a869a --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/pagers.py @@ -0,0 +1,3678 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.analytics.admin_v1alpha.types import analytics_admin +from google.analytics.admin_v1alpha.types import audience +from google.analytics.admin_v1alpha.types import channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set +from google.analytics.admin_v1alpha.types import resources +from google.analytics.admin_v1alpha.types import subproperty_event_filter + + +class ListAccountsPager: + """A pager for iterating through ``list_accounts`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAccountsResponse` + 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[..., analytics_admin.ListAccountsResponse], + request: analytics_admin.ListAccountsRequest, + response: analytics_admin.ListAccountsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAccountsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAccountsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccountsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListAccountsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.Account]: + for page in self.pages: + yield from page.accounts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountsAsyncPager: + """A pager for iterating through ``list_accounts`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAccountsResponse` + 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[analytics_admin.ListAccountsResponse]], + request: analytics_admin.ListAccountsRequest, + response: analytics_admin.ListAccountsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAccountsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAccountsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccountsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListAccountsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.Account]: + async def async_generator(): + async for page in self.pages: + for response in page.accounts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountSummariesPager: + """A pager for iterating through ``list_account_summaries`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAccountSummariesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``account_summaries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccountSummaries`` requests and continue to iterate + through the ``account_summaries`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAccountSummariesResponse` + 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[..., analytics_admin.ListAccountSummariesResponse], + request: analytics_admin.ListAccountSummariesRequest, + response: analytics_admin.ListAccountSummariesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAccountSummariesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAccountSummariesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccountSummariesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListAccountSummariesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.AccountSummary]: + for page in self.pages: + yield from page.account_summaries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountSummariesAsyncPager: + """A pager for iterating through ``list_account_summaries`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAccountSummariesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``account_summaries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccountSummaries`` requests and continue to iterate + through the ``account_summaries`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAccountSummariesResponse` + 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[analytics_admin.ListAccountSummariesResponse]], + request: analytics_admin.ListAccountSummariesRequest, + response: analytics_admin.ListAccountSummariesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAccountSummariesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAccountSummariesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccountSummariesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListAccountSummariesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.AccountSummary]: + async def async_generator(): + async for page in self.pages: + for response in page.account_summaries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPropertiesPager: + """A pager for iterating through ``list_properties`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListPropertiesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``properties`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProperties`` requests and continue to iterate + through the ``properties`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListPropertiesResponse` + 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[..., analytics_admin.ListPropertiesResponse], + request: analytics_admin.ListPropertiesRequest, + response: analytics_admin.ListPropertiesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListPropertiesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListPropertiesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListPropertiesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListPropertiesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.Property]: + for page in self.pages: + yield from page.properties + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPropertiesAsyncPager: + """A pager for iterating through ``list_properties`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListPropertiesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``properties`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProperties`` requests and continue to iterate + through the ``properties`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListPropertiesResponse` + 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[analytics_admin.ListPropertiesResponse]], + request: analytics_admin.ListPropertiesRequest, + response: analytics_admin.ListPropertiesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListPropertiesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListPropertiesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListPropertiesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListPropertiesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.Property]: + async def async_generator(): + async for page in self.pages: + for response in page.properties: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFirebaseLinksPager: + """A pager for iterating through ``list_firebase_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListFirebaseLinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``firebase_links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFirebaseLinks`` requests and continue to iterate + through the ``firebase_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListFirebaseLinksResponse` + 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[..., analytics_admin.ListFirebaseLinksResponse], + request: analytics_admin.ListFirebaseLinksRequest, + response: analytics_admin.ListFirebaseLinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListFirebaseLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListFirebaseLinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListFirebaseLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListFirebaseLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.FirebaseLink]: + for page in self.pages: + yield from page.firebase_links + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFirebaseLinksAsyncPager: + """A pager for iterating through ``list_firebase_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListFirebaseLinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``firebase_links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFirebaseLinks`` requests and continue to iterate + through the ``firebase_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListFirebaseLinksResponse` + 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[analytics_admin.ListFirebaseLinksResponse]], + request: analytics_admin.ListFirebaseLinksRequest, + response: analytics_admin.ListFirebaseLinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListFirebaseLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListFirebaseLinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListFirebaseLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListFirebaseLinksResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.FirebaseLink]: + async def async_generator(): + async for page in self.pages: + for response in page.firebase_links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGoogleAdsLinksPager: + """A pager for iterating through ``list_google_ads_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListGoogleAdsLinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``google_ads_links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGoogleAdsLinks`` requests and continue to iterate + through the ``google_ads_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListGoogleAdsLinksResponse` + 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[..., analytics_admin.ListGoogleAdsLinksResponse], + request: analytics_admin.ListGoogleAdsLinksRequest, + response: analytics_admin.ListGoogleAdsLinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListGoogleAdsLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListGoogleAdsLinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListGoogleAdsLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListGoogleAdsLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.GoogleAdsLink]: + for page in self.pages: + yield from page.google_ads_links + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGoogleAdsLinksAsyncPager: + """A pager for iterating through ``list_google_ads_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListGoogleAdsLinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``google_ads_links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGoogleAdsLinks`` requests and continue to iterate + through the ``google_ads_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListGoogleAdsLinksResponse` + 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[analytics_admin.ListGoogleAdsLinksResponse]], + request: analytics_admin.ListGoogleAdsLinksRequest, + response: analytics_admin.ListGoogleAdsLinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListGoogleAdsLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListGoogleAdsLinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListGoogleAdsLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListGoogleAdsLinksResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.GoogleAdsLink]: + async def async_generator(): + async for page in self.pages: + for response in page.google_ads_links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMeasurementProtocolSecretsPager: + """A pager for iterating through ``list_measurement_protocol_secrets`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``measurement_protocol_secrets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMeasurementProtocolSecrets`` requests and continue to iterate + through the ``measurement_protocol_secrets`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsResponse` + 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[..., analytics_admin.ListMeasurementProtocolSecretsResponse], + request: analytics_admin.ListMeasurementProtocolSecretsRequest, + response: analytics_admin.ListMeasurementProtocolSecretsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListMeasurementProtocolSecretsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListMeasurementProtocolSecretsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.MeasurementProtocolSecret]: + for page in self.pages: + yield from page.measurement_protocol_secrets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMeasurementProtocolSecretsAsyncPager: + """A pager for iterating through ``list_measurement_protocol_secrets`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``measurement_protocol_secrets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMeasurementProtocolSecrets`` requests and continue to iterate + through the ``measurement_protocol_secrets`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsResponse` + 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[analytics_admin.ListMeasurementProtocolSecretsResponse]], + request: analytics_admin.ListMeasurementProtocolSecretsRequest, + response: analytics_admin.ListMeasurementProtocolSecretsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListMeasurementProtocolSecretsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListMeasurementProtocolSecretsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListMeasurementProtocolSecretsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.MeasurementProtocolSecret]: + async def async_generator(): + async for page in self.pages: + for response in page.measurement_protocol_secrets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSKAdNetworkConversionValueSchemasPager: + """A pager for iterating through ``list_sk_ad_network_conversion_value_schemas`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasResponse` object, and + provides an ``__iter__`` method to iterate through its + ``skadnetwork_conversion_value_schemas`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSKAdNetworkConversionValueSchemas`` requests and continue to iterate + through the ``skadnetwork_conversion_value_schemas`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasResponse` + 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[..., analytics_admin.ListSKAdNetworkConversionValueSchemasResponse], + request: analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, + response: analytics_admin.ListSKAdNetworkConversionValueSchemasResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListSKAdNetworkConversionValueSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.SKAdNetworkConversionValueSchema]: + for page in self.pages: + yield from page.skadnetwork_conversion_value_schemas + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSKAdNetworkConversionValueSchemasAsyncPager: + """A pager for iterating through ``list_sk_ad_network_conversion_value_schemas`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``skadnetwork_conversion_value_schemas`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSKAdNetworkConversionValueSchemas`` requests and continue to iterate + through the ``skadnetwork_conversion_value_schemas`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasResponse` + 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[analytics_admin.ListSKAdNetworkConversionValueSchemasResponse]], + request: analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, + response: analytics_admin.ListSKAdNetworkConversionValueSchemasResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListSKAdNetworkConversionValueSchemasResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListSKAdNetworkConversionValueSchemasResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.SKAdNetworkConversionValueSchema]: + async def async_generator(): + async for page in self.pages: + for response in page.skadnetwork_conversion_value_schemas: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchChangeHistoryEventsPager: + """A pager for iterating through ``search_change_history_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``change_history_events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchChangeHistoryEvents`` requests and continue to iterate + through the ``change_history_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsResponse` + 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[..., analytics_admin.SearchChangeHistoryEventsResponse], + request: analytics_admin.SearchChangeHistoryEventsRequest, + response: analytics_admin.SearchChangeHistoryEventsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.SearchChangeHistoryEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.SearchChangeHistoryEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.ChangeHistoryEvent]: + for page in self.pages: + yield from page.change_history_events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchChangeHistoryEventsAsyncPager: + """A pager for iterating through ``search_change_history_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``change_history_events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchChangeHistoryEvents`` requests and continue to iterate + through the ``change_history_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsResponse` + 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[analytics_admin.SearchChangeHistoryEventsResponse]], + request: analytics_admin.SearchChangeHistoryEventsRequest, + response: analytics_admin.SearchChangeHistoryEventsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.SearchChangeHistoryEventsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.SearchChangeHistoryEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.SearchChangeHistoryEventsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.ChangeHistoryEvent]: + async def async_generator(): + async for page in self.pages: + for response in page.change_history_events: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversionEventsPager: + """A pager for iterating through ``list_conversion_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListConversionEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversion_events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversionEvents`` requests and continue to iterate + through the ``conversion_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListConversionEventsResponse` + 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[..., analytics_admin.ListConversionEventsResponse], + request: analytics_admin.ListConversionEventsRequest, + response: analytics_admin.ListConversionEventsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListConversionEventsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListConversionEventsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListConversionEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListConversionEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.ConversionEvent]: + for page in self.pages: + yield from page.conversion_events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversionEventsAsyncPager: + """A pager for iterating through ``list_conversion_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListConversionEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversion_events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversionEvents`` requests and continue to iterate + through the ``conversion_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListConversionEventsResponse` + 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[analytics_admin.ListConversionEventsResponse]], + request: analytics_admin.ListConversionEventsRequest, + response: analytics_admin.ListConversionEventsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListConversionEventsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListConversionEventsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListConversionEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListConversionEventsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.ConversionEvent]: + async def async_generator(): + async for page in self.pages: + for response in page.conversion_events: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListKeyEventsPager: + """A pager for iterating through ``list_key_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListKeyEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``key_events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListKeyEvents`` requests and continue to iterate + through the ``key_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListKeyEventsResponse` + 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[..., analytics_admin.ListKeyEventsResponse], + request: analytics_admin.ListKeyEventsRequest, + response: analytics_admin.ListKeyEventsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListKeyEventsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListKeyEventsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListKeyEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListKeyEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.KeyEvent]: + for page in self.pages: + yield from page.key_events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListKeyEventsAsyncPager: + """A pager for iterating through ``list_key_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListKeyEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``key_events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListKeyEvents`` requests and continue to iterate + through the ``key_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListKeyEventsResponse` + 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[analytics_admin.ListKeyEventsResponse]], + request: analytics_admin.ListKeyEventsRequest, + response: analytics_admin.ListKeyEventsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListKeyEventsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListKeyEventsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListKeyEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListKeyEventsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.KeyEvent]: + async def async_generator(): + async for page in self.pages: + for response in page.key_events: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDisplayVideo360AdvertiserLinksPager: + """A pager for iterating through ``list_display_video360_advertiser_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``display_video_360_advertiser_links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDisplayVideo360AdvertiserLinks`` requests and continue to iterate + through the ``display_video_360_advertiser_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksResponse` + 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[..., analytics_admin.ListDisplayVideo360AdvertiserLinksResponse], + request: analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, + response: analytics_admin.ListDisplayVideo360AdvertiserLinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListDisplayVideo360AdvertiserLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.DisplayVideo360AdvertiserLink]: + for page in self.pages: + yield from page.display_video_360_advertiser_links + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDisplayVideo360AdvertiserLinksAsyncPager: + """A pager for iterating through ``list_display_video360_advertiser_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``display_video_360_advertiser_links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDisplayVideo360AdvertiserLinks`` requests and continue to iterate + through the ``display_video_360_advertiser_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksResponse` + 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[analytics_admin.ListDisplayVideo360AdvertiserLinksResponse]], + request: analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, + response: analytics_admin.ListDisplayVideo360AdvertiserLinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListDisplayVideo360AdvertiserLinksResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.DisplayVideo360AdvertiserLink]: + async def async_generator(): + async for page in self.pages: + for response in page.display_video_360_advertiser_links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDisplayVideo360AdvertiserLinkProposalsPager: + """A pager for iterating through ``list_display_video360_advertiser_link_proposals`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``display_video_360_advertiser_link_proposals`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDisplayVideo360AdvertiserLinkProposals`` requests and continue to iterate + through the ``display_video_360_advertiser_link_proposals`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsResponse` + 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[..., analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse], + request: analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, + response: analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.DisplayVideo360AdvertiserLinkProposal]: + for page in self.pages: + yield from page.display_video_360_advertiser_link_proposals + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDisplayVideo360AdvertiserLinkProposalsAsyncPager: + """A pager for iterating through ``list_display_video360_advertiser_link_proposals`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``display_video_360_advertiser_link_proposals`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDisplayVideo360AdvertiserLinkProposals`` requests and continue to iterate + through the ``display_video_360_advertiser_link_proposals`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsResponse` + 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[analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse]], + request: analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, + response: analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinkProposalsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.DisplayVideo360AdvertiserLinkProposal]: + async def async_generator(): + async for page in self.pages: + for response in page.display_video_360_advertiser_link_proposals: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCustomDimensionsPager: + """A pager for iterating through ``list_custom_dimensions`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListCustomDimensionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``custom_dimensions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCustomDimensions`` requests and continue to iterate + through the ``custom_dimensions`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListCustomDimensionsResponse` + 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[..., analytics_admin.ListCustomDimensionsResponse], + request: analytics_admin.ListCustomDimensionsRequest, + response: analytics_admin.ListCustomDimensionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListCustomDimensionsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListCustomDimensionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCustomDimensionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListCustomDimensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.CustomDimension]: + for page in self.pages: + yield from page.custom_dimensions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCustomDimensionsAsyncPager: + """A pager for iterating through ``list_custom_dimensions`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListCustomDimensionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``custom_dimensions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCustomDimensions`` requests and continue to iterate + through the ``custom_dimensions`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListCustomDimensionsResponse` + 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[analytics_admin.ListCustomDimensionsResponse]], + request: analytics_admin.ListCustomDimensionsRequest, + response: analytics_admin.ListCustomDimensionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListCustomDimensionsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListCustomDimensionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCustomDimensionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListCustomDimensionsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.CustomDimension]: + async def async_generator(): + async for page in self.pages: + for response in page.custom_dimensions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCustomMetricsPager: + """A pager for iterating through ``list_custom_metrics`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListCustomMetricsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``custom_metrics`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCustomMetrics`` requests and continue to iterate + through the ``custom_metrics`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListCustomMetricsResponse` + 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[..., analytics_admin.ListCustomMetricsResponse], + request: analytics_admin.ListCustomMetricsRequest, + response: analytics_admin.ListCustomMetricsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListCustomMetricsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListCustomMetricsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCustomMetricsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListCustomMetricsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.CustomMetric]: + for page in self.pages: + yield from page.custom_metrics + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCustomMetricsAsyncPager: + """A pager for iterating through ``list_custom_metrics`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListCustomMetricsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``custom_metrics`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCustomMetrics`` requests and continue to iterate + through the ``custom_metrics`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListCustomMetricsResponse` + 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[analytics_admin.ListCustomMetricsResponse]], + request: analytics_admin.ListCustomMetricsRequest, + response: analytics_admin.ListCustomMetricsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListCustomMetricsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListCustomMetricsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCustomMetricsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListCustomMetricsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.CustomMetric]: + async def async_generator(): + async for page in self.pages: + for response in page.custom_metrics: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataStreamsPager: + """A pager for iterating through ``list_data_streams`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListDataStreamsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_streams`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataStreams`` requests and continue to iterate + through the ``data_streams`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListDataStreamsResponse` + 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[..., analytics_admin.ListDataStreamsResponse], + request: analytics_admin.ListDataStreamsRequest, + response: analytics_admin.ListDataStreamsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListDataStreamsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListDataStreamsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListDataStreamsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListDataStreamsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.DataStream]: + for page in self.pages: + yield from page.data_streams + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataStreamsAsyncPager: + """A pager for iterating through ``list_data_streams`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListDataStreamsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_streams`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataStreams`` requests and continue to iterate + through the ``data_streams`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListDataStreamsResponse` + 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[analytics_admin.ListDataStreamsResponse]], + request: analytics_admin.ListDataStreamsRequest, + response: analytics_admin.ListDataStreamsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListDataStreamsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListDataStreamsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListDataStreamsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListDataStreamsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.DataStream]: + async def async_generator(): + async for page in self.pages: + for response in page.data_streams: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAudiencesPager: + """A pager for iterating through ``list_audiences`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAudiencesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``audiences`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAudiences`` requests and continue to iterate + through the ``audiences`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAudiencesResponse` + 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[..., analytics_admin.ListAudiencesResponse], + request: analytics_admin.ListAudiencesRequest, + response: analytics_admin.ListAudiencesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAudiencesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAudiencesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAudiencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListAudiencesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[audience.Audience]: + for page in self.pages: + yield from page.audiences + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAudiencesAsyncPager: + """A pager for iterating through ``list_audiences`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAudiencesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``audiences`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAudiences`` requests and continue to iterate + through the ``audiences`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAudiencesResponse` + 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[analytics_admin.ListAudiencesResponse]], + request: analytics_admin.ListAudiencesRequest, + response: analytics_admin.ListAudiencesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAudiencesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAudiencesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAudiencesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListAudiencesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[audience.Audience]: + async def async_generator(): + async for page in self.pages: + for response in page.audiences: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSearchAds360LinksPager: + """A pager for iterating through ``list_search_ads360_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListSearchAds360LinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``search_ads_360_links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSearchAds360Links`` requests and continue to iterate + through the ``search_ads_360_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListSearchAds360LinksResponse` + 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[..., analytics_admin.ListSearchAds360LinksResponse], + request: analytics_admin.ListSearchAds360LinksRequest, + response: analytics_admin.ListSearchAds360LinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListSearchAds360LinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListSearchAds360LinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListSearchAds360LinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListSearchAds360LinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.SearchAds360Link]: + for page in self.pages: + yield from page.search_ads_360_links + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSearchAds360LinksAsyncPager: + """A pager for iterating through ``list_search_ads360_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListSearchAds360LinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``search_ads_360_links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSearchAds360Links`` requests and continue to iterate + through the ``search_ads_360_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListSearchAds360LinksResponse` + 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[analytics_admin.ListSearchAds360LinksResponse]], + request: analytics_admin.ListSearchAds360LinksRequest, + response: analytics_admin.ListSearchAds360LinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListSearchAds360LinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListSearchAds360LinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListSearchAds360LinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListSearchAds360LinksResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.SearchAds360Link]: + async def async_generator(): + async for page in self.pages: + for response in page.search_ads_360_links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccessBindingsPager: + """A pager for iterating through ``list_access_bindings`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAccessBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``access_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccessBindings`` requests and continue to iterate + through the ``access_bindings`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAccessBindingsResponse` + 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[..., analytics_admin.ListAccessBindingsResponse], + request: analytics_admin.ListAccessBindingsRequest, + response: analytics_admin.ListAccessBindingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAccessBindingsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAccessBindingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccessBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListAccessBindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.AccessBinding]: + for page in self.pages: + yield from page.access_bindings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccessBindingsAsyncPager: + """A pager for iterating through ``list_access_bindings`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAccessBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``access_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccessBindings`` requests and continue to iterate + through the ``access_bindings`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAccessBindingsResponse` + 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[analytics_admin.ListAccessBindingsResponse]], + request: analytics_admin.ListAccessBindingsRequest, + response: analytics_admin.ListAccessBindingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAccessBindingsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAccessBindingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccessBindingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListAccessBindingsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.AccessBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.access_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListExpandedDataSetsPager: + """A pager for iterating through ``list_expanded_data_sets`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListExpandedDataSetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``expanded_data_sets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExpandedDataSets`` requests and continue to iterate + through the ``expanded_data_sets`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListExpandedDataSetsResponse` + 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[..., analytics_admin.ListExpandedDataSetsResponse], + request: analytics_admin.ListExpandedDataSetsRequest, + response: analytics_admin.ListExpandedDataSetsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListExpandedDataSetsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListExpandedDataSetsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListExpandedDataSetsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListExpandedDataSetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[expanded_data_set.ExpandedDataSet]: + for page in self.pages: + yield from page.expanded_data_sets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListExpandedDataSetsAsyncPager: + """A pager for iterating through ``list_expanded_data_sets`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListExpandedDataSetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``expanded_data_sets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExpandedDataSets`` requests and continue to iterate + through the ``expanded_data_sets`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListExpandedDataSetsResponse` + 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[analytics_admin.ListExpandedDataSetsResponse]], + request: analytics_admin.ListExpandedDataSetsRequest, + response: analytics_admin.ListExpandedDataSetsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListExpandedDataSetsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListExpandedDataSetsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListExpandedDataSetsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListExpandedDataSetsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[expanded_data_set.ExpandedDataSet]: + async def async_generator(): + async for page in self.pages: + for response in page.expanded_data_sets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListChannelGroupsPager: + """A pager for iterating through ``list_channel_groups`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListChannelGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``channel_groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListChannelGroups`` requests and continue to iterate + through the ``channel_groups`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListChannelGroupsResponse` + 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[..., analytics_admin.ListChannelGroupsResponse], + request: analytics_admin.ListChannelGroupsRequest, + response: analytics_admin.ListChannelGroupsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListChannelGroupsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListChannelGroupsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListChannelGroupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListChannelGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[channel_group.ChannelGroup]: + for page in self.pages: + yield from page.channel_groups + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListChannelGroupsAsyncPager: + """A pager for iterating through ``list_channel_groups`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListChannelGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``channel_groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListChannelGroups`` requests and continue to iterate + through the ``channel_groups`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListChannelGroupsResponse` + 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[analytics_admin.ListChannelGroupsResponse]], + request: analytics_admin.ListChannelGroupsRequest, + response: analytics_admin.ListChannelGroupsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListChannelGroupsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListChannelGroupsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListChannelGroupsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListChannelGroupsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[channel_group.ChannelGroup]: + async def async_generator(): + async for page in self.pages: + for response in page.channel_groups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryLinksPager: + """A pager for iterating through ``list_big_query_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListBigQueryLinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``bigquery_links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBigQueryLinks`` requests and continue to iterate + through the ``bigquery_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListBigQueryLinksResponse` + 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[..., analytics_admin.ListBigQueryLinksResponse], + request: analytics_admin.ListBigQueryLinksRequest, + response: analytics_admin.ListBigQueryLinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListBigQueryLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListBigQueryLinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListBigQueryLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListBigQueryLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.BigQueryLink]: + for page in self.pages: + yield from page.bigquery_links + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListBigQueryLinksAsyncPager: + """A pager for iterating through ``list_big_query_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListBigQueryLinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``bigquery_links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBigQueryLinks`` requests and continue to iterate + through the ``bigquery_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListBigQueryLinksResponse` + 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[analytics_admin.ListBigQueryLinksResponse]], + request: analytics_admin.ListBigQueryLinksRequest, + response: analytics_admin.ListBigQueryLinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListBigQueryLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListBigQueryLinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListBigQueryLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListBigQueryLinksResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.BigQueryLink]: + async def async_generator(): + async for page in self.pages: + for response in page.bigquery_links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAdSenseLinksPager: + """A pager for iterating through ``list_ad_sense_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAdSenseLinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``adsense_links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAdSenseLinks`` requests and continue to iterate + through the ``adsense_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAdSenseLinksResponse` + 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[..., analytics_admin.ListAdSenseLinksResponse], + request: analytics_admin.ListAdSenseLinksRequest, + response: analytics_admin.ListAdSenseLinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAdSenseLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAdSenseLinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAdSenseLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListAdSenseLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.AdSenseLink]: + for page in self.pages: + yield from page.adsense_links + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAdSenseLinksAsyncPager: + """A pager for iterating through ``list_ad_sense_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListAdSenseLinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``adsense_links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAdSenseLinks`` requests and continue to iterate + through the ``adsense_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListAdSenseLinksResponse` + 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[analytics_admin.ListAdSenseLinksResponse]], + request: analytics_admin.ListAdSenseLinksRequest, + response: analytics_admin.ListAdSenseLinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListAdSenseLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListAdSenseLinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAdSenseLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListAdSenseLinksResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.AdSenseLink]: + async def async_generator(): + async for page in self.pages: + for response in page.adsense_links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventCreateRulesPager: + """A pager for iterating through ``list_event_create_rules`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListEventCreateRulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``event_create_rules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEventCreateRules`` requests and continue to iterate + through the ``event_create_rules`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListEventCreateRulesResponse` + 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[..., analytics_admin.ListEventCreateRulesResponse], + request: analytics_admin.ListEventCreateRulesRequest, + response: analytics_admin.ListEventCreateRulesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListEventCreateRulesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListEventCreateRulesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListEventCreateRulesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListEventCreateRulesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[event_create_and_edit.EventCreateRule]: + for page in self.pages: + yield from page.event_create_rules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventCreateRulesAsyncPager: + """A pager for iterating through ``list_event_create_rules`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListEventCreateRulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``event_create_rules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEventCreateRules`` requests and continue to iterate + through the ``event_create_rules`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListEventCreateRulesResponse` + 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[analytics_admin.ListEventCreateRulesResponse]], + request: analytics_admin.ListEventCreateRulesRequest, + response: analytics_admin.ListEventCreateRulesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListEventCreateRulesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListEventCreateRulesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListEventCreateRulesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListEventCreateRulesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[event_create_and_edit.EventCreateRule]: + async def async_generator(): + async for page in self.pages: + for response in page.event_create_rules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventEditRulesPager: + """A pager for iterating through ``list_event_edit_rules`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListEventEditRulesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``event_edit_rules`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEventEditRules`` requests and continue to iterate + through the ``event_edit_rules`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListEventEditRulesResponse` + 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[..., analytics_admin.ListEventEditRulesResponse], + request: analytics_admin.ListEventEditRulesRequest, + response: analytics_admin.ListEventEditRulesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListEventEditRulesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListEventEditRulesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListEventEditRulesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListEventEditRulesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[event_create_and_edit.EventEditRule]: + for page in self.pages: + yield from page.event_edit_rules + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEventEditRulesAsyncPager: + """A pager for iterating through ``list_event_edit_rules`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListEventEditRulesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``event_edit_rules`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEventEditRules`` requests and continue to iterate + through the ``event_edit_rules`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListEventEditRulesResponse` + 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[analytics_admin.ListEventEditRulesResponse]], + request: analytics_admin.ListEventEditRulesRequest, + response: analytics_admin.ListEventEditRulesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListEventEditRulesRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListEventEditRulesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListEventEditRulesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListEventEditRulesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[event_create_and_edit.EventEditRule]: + async def async_generator(): + async for page in self.pages: + for response in page.event_edit_rules: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCalculatedMetricsPager: + """A pager for iterating through ``list_calculated_metrics`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListCalculatedMetricsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``calculated_metrics`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCalculatedMetrics`` requests and continue to iterate + through the ``calculated_metrics`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListCalculatedMetricsResponse` + 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[..., analytics_admin.ListCalculatedMetricsResponse], + request: analytics_admin.ListCalculatedMetricsRequest, + response: analytics_admin.ListCalculatedMetricsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListCalculatedMetricsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListCalculatedMetricsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCalculatedMetricsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListCalculatedMetricsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.CalculatedMetric]: + for page in self.pages: + yield from page.calculated_metrics + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCalculatedMetricsAsyncPager: + """A pager for iterating through ``list_calculated_metrics`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListCalculatedMetricsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``calculated_metrics`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCalculatedMetrics`` requests and continue to iterate + through the ``calculated_metrics`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListCalculatedMetricsResponse` + 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[analytics_admin.ListCalculatedMetricsResponse]], + request: analytics_admin.ListCalculatedMetricsRequest, + response: analytics_admin.ListCalculatedMetricsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListCalculatedMetricsRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListCalculatedMetricsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCalculatedMetricsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListCalculatedMetricsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.CalculatedMetric]: + async def async_generator(): + async for page in self.pages: + for response in page.calculated_metrics: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRollupPropertySourceLinksPager: + """A pager for iterating through ``list_rollup_property_source_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``rollup_property_source_links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRollupPropertySourceLinks`` requests and continue to iterate + through the ``rollup_property_source_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksResponse` + 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[..., analytics_admin.ListRollupPropertySourceLinksResponse], + request: analytics_admin.ListRollupPropertySourceLinksRequest, + response: analytics_admin.ListRollupPropertySourceLinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListRollupPropertySourceLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListRollupPropertySourceLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.RollupPropertySourceLink]: + for page in self.pages: + yield from page.rollup_property_source_links + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListRollupPropertySourceLinksAsyncPager: + """A pager for iterating through ``list_rollup_property_source_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``rollup_property_source_links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRollupPropertySourceLinks`` requests and continue to iterate + through the ``rollup_property_source_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksResponse` + 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[analytics_admin.ListRollupPropertySourceLinksResponse]], + request: analytics_admin.ListRollupPropertySourceLinksRequest, + response: analytics_admin.ListRollupPropertySourceLinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListRollupPropertySourceLinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListRollupPropertySourceLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListRollupPropertySourceLinksResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.RollupPropertySourceLink]: + async def async_generator(): + async for page in self.pages: + for response in page.rollup_property_source_links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSubpropertyEventFiltersPager: + """A pager for iterating through ``list_subproperty_event_filters`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``subproperty_event_filters`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSubpropertyEventFilters`` requests and continue to iterate + through the ``subproperty_event_filters`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersResponse` + 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[..., analytics_admin.ListSubpropertyEventFiltersResponse], + request: analytics_admin.ListSubpropertyEventFiltersRequest, + response: analytics_admin.ListSubpropertyEventFiltersResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListSubpropertyEventFiltersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListSubpropertyEventFiltersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[subproperty_event_filter.SubpropertyEventFilter]: + for page in self.pages: + yield from page.subproperty_event_filters + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSubpropertyEventFiltersAsyncPager: + """A pager for iterating through ``list_subproperty_event_filters`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``subproperty_event_filters`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSubpropertyEventFilters`` requests and continue to iterate + through the ``subproperty_event_filters`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersResponse` + 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[analytics_admin.ListSubpropertyEventFiltersResponse]], + request: analytics_admin.ListSubpropertyEventFiltersRequest, + response: analytics_admin.ListSubpropertyEventFiltersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersRequest): + The initial request object. + response (google.analytics.admin_v1alpha.types.ListSubpropertyEventFiltersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListSubpropertyEventFiltersRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListSubpropertyEventFiltersResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[subproperty_event_filter.SubpropertyEventFilter]: + async def async_generator(): + async for page in self.pages: + for response in page.subproperty_event_filters: + 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-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/__init__.py new file mode 100644 index 000000000000..76ffdcce4f9c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_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 AnalyticsAdminServiceTransport +from .grpc import AnalyticsAdminServiceGrpcTransport +from .grpc_asyncio import AnalyticsAdminServiceGrpcAsyncIOTransport +from .rest import AnalyticsAdminServiceRestTransport +from .rest import AnalyticsAdminServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AnalyticsAdminServiceTransport]] +_transport_registry['grpc'] = AnalyticsAdminServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AnalyticsAdminServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AnalyticsAdminServiceRestTransport + +__all__ = ( + 'AnalyticsAdminServiceTransport', + 'AnalyticsAdminServiceGrpcTransport', + 'AnalyticsAdminServiceGrpcAsyncIOTransport', + 'AnalyticsAdminServiceRestTransport', + 'AnalyticsAdminServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/base.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/base.py new file mode 100644 index 000000000000..8f9a00d46c63 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/base.py @@ -0,0 +1,2254 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1alpha 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.analytics.admin_v1alpha.types import analytics_admin +from google.analytics.admin_v1alpha.types import audience +from google.analytics.admin_v1alpha.types import audience as gaa_audience +from google.analytics.admin_v1alpha.types import channel_group +from google.analytics.admin_v1alpha.types import channel_group as gaa_channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set +from google.analytics.admin_v1alpha.types import expanded_data_set as gaa_expanded_data_set +from google.analytics.admin_v1alpha.types import resources +from google.analytics.admin_v1alpha.types import subproperty_event_filter +from google.analytics.admin_v1alpha.types import subproperty_event_filter as gaa_subproperty_event_filter +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AnalyticsAdminServiceTransport(abc.ABC): + """Abstract transport class for AnalyticsAdminService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/analytics.edit', + 'https://www.googleapis.com/auth/analytics.manage.users', + 'https://www.googleapis.com/auth/analytics.manage.users.readonly', + 'https://www.googleapis.com/auth/analytics.readonly', + ) + + DEFAULT_HOST: str = 'analyticsadmin.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: 'analyticsadmin.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 not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + 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.get_account: gapic_v1.method.wrap_method( + self.get_account, + default_timeout=60.0, + client_info=client_info, + ), + self.list_accounts: gapic_v1.method.wrap_method( + self.list_accounts, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_account: gapic_v1.method.wrap_method( + self.delete_account, + default_timeout=60.0, + client_info=client_info, + ), + self.update_account: gapic_v1.method.wrap_method( + self.update_account, + default_timeout=60.0, + client_info=client_info, + ), + self.provision_account_ticket: gapic_v1.method.wrap_method( + self.provision_account_ticket, + default_timeout=60.0, + client_info=client_info, + ), + self.list_account_summaries: gapic_v1.method.wrap_method( + self.list_account_summaries, + default_timeout=None, + client_info=client_info, + ), + self.get_property: gapic_v1.method.wrap_method( + self.get_property, + default_timeout=60.0, + client_info=client_info, + ), + self.list_properties: gapic_v1.method.wrap_method( + self.list_properties, + default_timeout=60.0, + client_info=client_info, + ), + self.create_property: gapic_v1.method.wrap_method( + self.create_property, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_property: gapic_v1.method.wrap_method( + self.delete_property, + default_timeout=60.0, + client_info=client_info, + ), + self.update_property: gapic_v1.method.wrap_method( + self.update_property, + default_timeout=60.0, + client_info=client_info, + ), + self.create_firebase_link: gapic_v1.method.wrap_method( + self.create_firebase_link, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_firebase_link: gapic_v1.method.wrap_method( + self.delete_firebase_link, + default_timeout=60.0, + client_info=client_info, + ), + self.list_firebase_links: gapic_v1.method.wrap_method( + self.list_firebase_links, + default_timeout=60.0, + client_info=client_info, + ), + self.get_global_site_tag: gapic_v1.method.wrap_method( + self.get_global_site_tag, + default_timeout=60.0, + client_info=client_info, + ), + self.create_google_ads_link: gapic_v1.method.wrap_method( + self.create_google_ads_link, + default_timeout=60.0, + client_info=client_info, + ), + self.update_google_ads_link: gapic_v1.method.wrap_method( + self.update_google_ads_link, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_google_ads_link: gapic_v1.method.wrap_method( + self.delete_google_ads_link, + default_timeout=60.0, + client_info=client_info, + ), + self.list_google_ads_links: gapic_v1.method.wrap_method( + self.list_google_ads_links, + default_timeout=60.0, + client_info=client_info, + ), + self.get_data_sharing_settings: gapic_v1.method.wrap_method( + self.get_data_sharing_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_measurement_protocol_secret: gapic_v1.method.wrap_method( + self.get_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_measurement_protocol_secrets: gapic_v1.method.wrap_method( + self.list_measurement_protocol_secrets, + default_timeout=None, + client_info=client_info, + ), + self.create_measurement_protocol_secret: gapic_v1.method.wrap_method( + self.create_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_measurement_protocol_secret: gapic_v1.method.wrap_method( + self.delete_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.update_measurement_protocol_secret: gapic_v1.method.wrap_method( + self.update_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.acknowledge_user_data_collection: gapic_v1.method.wrap_method( + self.acknowledge_user_data_collection, + default_timeout=None, + client_info=client_info, + ), + self.get_sk_ad_network_conversion_value_schema: gapic_v1.method.wrap_method( + self.get_sk_ad_network_conversion_value_schema, + default_timeout=None, + client_info=client_info, + ), + self.create_sk_ad_network_conversion_value_schema: gapic_v1.method.wrap_method( + self.create_sk_ad_network_conversion_value_schema, + default_timeout=None, + client_info=client_info, + ), + self.delete_sk_ad_network_conversion_value_schema: gapic_v1.method.wrap_method( + self.delete_sk_ad_network_conversion_value_schema, + default_timeout=None, + client_info=client_info, + ), + self.update_sk_ad_network_conversion_value_schema: gapic_v1.method.wrap_method( + self.update_sk_ad_network_conversion_value_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_sk_ad_network_conversion_value_schemas: gapic_v1.method.wrap_method( + self.list_sk_ad_network_conversion_value_schemas, + default_timeout=None, + client_info=client_info, + ), + self.search_change_history_events: gapic_v1.method.wrap_method( + self.search_change_history_events, + default_timeout=None, + client_info=client_info, + ), + self.get_google_signals_settings: gapic_v1.method.wrap_method( + self.get_google_signals_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_google_signals_settings: gapic_v1.method.wrap_method( + self.update_google_signals_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_conversion_event: gapic_v1.method.wrap_method( + self.create_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.update_conversion_event: gapic_v1.method.wrap_method( + self.update_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.get_conversion_event: gapic_v1.method.wrap_method( + self.get_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversion_event: gapic_v1.method.wrap_method( + self.delete_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.list_conversion_events: gapic_v1.method.wrap_method( + self.list_conversion_events, + default_timeout=None, + client_info=client_info, + ), + self.create_key_event: gapic_v1.method.wrap_method( + self.create_key_event, + default_timeout=None, + client_info=client_info, + ), + self.update_key_event: gapic_v1.method.wrap_method( + self.update_key_event, + default_timeout=None, + client_info=client_info, + ), + self.get_key_event: gapic_v1.method.wrap_method( + self.get_key_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_key_event: gapic_v1.method.wrap_method( + self.delete_key_event, + default_timeout=None, + client_info=client_info, + ), + self.list_key_events: gapic_v1.method.wrap_method( + self.list_key_events, + default_timeout=None, + client_info=client_info, + ), + self.get_display_video360_advertiser_link: gapic_v1.method.wrap_method( + self.get_display_video360_advertiser_link, + default_timeout=None, + client_info=client_info, + ), + self.list_display_video360_advertiser_links: gapic_v1.method.wrap_method( + self.list_display_video360_advertiser_links, + default_timeout=None, + client_info=client_info, + ), + self.create_display_video360_advertiser_link: gapic_v1.method.wrap_method( + self.create_display_video360_advertiser_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_display_video360_advertiser_link: gapic_v1.method.wrap_method( + self.delete_display_video360_advertiser_link, + default_timeout=None, + client_info=client_info, + ), + self.update_display_video360_advertiser_link: gapic_v1.method.wrap_method( + self.update_display_video360_advertiser_link, + default_timeout=None, + client_info=client_info, + ), + self.get_display_video360_advertiser_link_proposal: gapic_v1.method.wrap_method( + self.get_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.list_display_video360_advertiser_link_proposals: gapic_v1.method.wrap_method( + self.list_display_video360_advertiser_link_proposals, + default_timeout=None, + client_info=client_info, + ), + self.create_display_video360_advertiser_link_proposal: gapic_v1.method.wrap_method( + self.create_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.delete_display_video360_advertiser_link_proposal: gapic_v1.method.wrap_method( + self.delete_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.approve_display_video360_advertiser_link_proposal: gapic_v1.method.wrap_method( + self.approve_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.cancel_display_video360_advertiser_link_proposal: gapic_v1.method.wrap_method( + self.cancel_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.create_custom_dimension: gapic_v1.method.wrap_method( + self.create_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.update_custom_dimension: gapic_v1.method.wrap_method( + self.update_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.list_custom_dimensions: gapic_v1.method.wrap_method( + self.list_custom_dimensions, + default_timeout=None, + client_info=client_info, + ), + self.archive_custom_dimension: gapic_v1.method.wrap_method( + self.archive_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.get_custom_dimension: gapic_v1.method.wrap_method( + self.get_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.create_custom_metric: gapic_v1.method.wrap_method( + self.create_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.update_custom_metric: gapic_v1.method.wrap_method( + self.update_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.list_custom_metrics: gapic_v1.method.wrap_method( + self.list_custom_metrics, + default_timeout=None, + client_info=client_info, + ), + self.archive_custom_metric: gapic_v1.method.wrap_method( + self.archive_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.get_custom_metric: gapic_v1.method.wrap_method( + self.get_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.get_data_retention_settings: gapic_v1.method.wrap_method( + self.get_data_retention_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_data_retention_settings: gapic_v1.method.wrap_method( + self.update_data_retention_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_data_stream: gapic_v1.method.wrap_method( + self.create_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_stream: gapic_v1.method.wrap_method( + self.delete_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.update_data_stream: gapic_v1.method.wrap_method( + self.update_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.list_data_streams: gapic_v1.method.wrap_method( + self.list_data_streams, + default_timeout=None, + client_info=client_info, + ), + self.get_data_stream: gapic_v1.method.wrap_method( + self.get_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.get_audience: gapic_v1.method.wrap_method( + self.get_audience, + default_timeout=None, + client_info=client_info, + ), + self.list_audiences: gapic_v1.method.wrap_method( + self.list_audiences, + default_timeout=None, + client_info=client_info, + ), + self.create_audience: gapic_v1.method.wrap_method( + self.create_audience, + default_timeout=None, + client_info=client_info, + ), + self.update_audience: gapic_v1.method.wrap_method( + self.update_audience, + default_timeout=None, + client_info=client_info, + ), + self.archive_audience: gapic_v1.method.wrap_method( + self.archive_audience, + default_timeout=None, + client_info=client_info, + ), + self.get_search_ads360_link: gapic_v1.method.wrap_method( + self.get_search_ads360_link, + default_timeout=None, + client_info=client_info, + ), + self.list_search_ads360_links: gapic_v1.method.wrap_method( + self.list_search_ads360_links, + default_timeout=None, + client_info=client_info, + ), + self.create_search_ads360_link: gapic_v1.method.wrap_method( + self.create_search_ads360_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_search_ads360_link: gapic_v1.method.wrap_method( + self.delete_search_ads360_link, + default_timeout=None, + client_info=client_info, + ), + self.update_search_ads360_link: gapic_v1.method.wrap_method( + self.update_search_ads360_link, + default_timeout=None, + client_info=client_info, + ), + self.get_attribution_settings: gapic_v1.method.wrap_method( + self.get_attribution_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_attribution_settings: gapic_v1.method.wrap_method( + self.update_attribution_settings, + default_timeout=None, + client_info=client_info, + ), + self.run_access_report: gapic_v1.method.wrap_method( + self.run_access_report, + default_timeout=None, + client_info=client_info, + ), + self.create_access_binding: gapic_v1.method.wrap_method( + self.create_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.get_access_binding: gapic_v1.method.wrap_method( + self.get_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_access_binding: gapic_v1.method.wrap_method( + self.update_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_access_binding: gapic_v1.method.wrap_method( + self.delete_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_access_bindings: gapic_v1.method.wrap_method( + self.list_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_access_bindings: gapic_v1.method.wrap_method( + self.batch_create_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_access_bindings: gapic_v1.method.wrap_method( + self.batch_get_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_access_bindings: gapic_v1.method.wrap_method( + self.batch_update_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_access_bindings: gapic_v1.method.wrap_method( + self.batch_delete_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_expanded_data_set: gapic_v1.method.wrap_method( + self.get_expanded_data_set, + default_timeout=None, + client_info=client_info, + ), + self.list_expanded_data_sets: gapic_v1.method.wrap_method( + self.list_expanded_data_sets, + default_timeout=None, + client_info=client_info, + ), + self.create_expanded_data_set: gapic_v1.method.wrap_method( + self.create_expanded_data_set, + default_timeout=None, + client_info=client_info, + ), + self.update_expanded_data_set: gapic_v1.method.wrap_method( + self.update_expanded_data_set, + default_timeout=None, + client_info=client_info, + ), + self.delete_expanded_data_set: gapic_v1.method.wrap_method( + self.delete_expanded_data_set, + default_timeout=None, + client_info=client_info, + ), + self.get_channel_group: gapic_v1.method.wrap_method( + self.get_channel_group, + default_timeout=None, + client_info=client_info, + ), + self.list_channel_groups: gapic_v1.method.wrap_method( + self.list_channel_groups, + default_timeout=None, + client_info=client_info, + ), + self.create_channel_group: gapic_v1.method.wrap_method( + self.create_channel_group, + default_timeout=None, + client_info=client_info, + ), + self.update_channel_group: gapic_v1.method.wrap_method( + self.update_channel_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_channel_group: gapic_v1.method.wrap_method( + self.delete_channel_group, + default_timeout=None, + client_info=client_info, + ), + self.set_automated_ga4_configuration_opt_out: gapic_v1.method.wrap_method( + self.set_automated_ga4_configuration_opt_out, + default_timeout=None, + client_info=client_info, + ), + self.fetch_automated_ga4_configuration_opt_out: gapic_v1.method.wrap_method( + self.fetch_automated_ga4_configuration_opt_out, + default_timeout=None, + client_info=client_info, + ), + self.create_big_query_link: gapic_v1.method.wrap_method( + self.create_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_link: gapic_v1.method.wrap_method( + self.get_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_links: gapic_v1.method.wrap_method( + self.list_big_query_links, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_link: gapic_v1.method.wrap_method( + self.delete_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_link: gapic_v1.method.wrap_method( + self.update_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.get_enhanced_measurement_settings: gapic_v1.method.wrap_method( + self.get_enhanced_measurement_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_enhanced_measurement_settings: gapic_v1.method.wrap_method( + self.update_enhanced_measurement_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.create_connected_site_tag: gapic_v1.method.wrap_method( + self.create_connected_site_tag, + default_timeout=None, + client_info=client_info, + ), + self.delete_connected_site_tag: gapic_v1.method.wrap_method( + self.delete_connected_site_tag, + default_timeout=None, + client_info=client_info, + ), + self.list_connected_site_tags: gapic_v1.method.wrap_method( + self.list_connected_site_tags, + default_timeout=None, + client_info=client_info, + ), + self.fetch_connected_ga4_property: gapic_v1.method.wrap_method( + self.fetch_connected_ga4_property, + default_timeout=None, + client_info=client_info, + ), + self.get_ad_sense_link: gapic_v1.method.wrap_method( + self.get_ad_sense_link, + default_timeout=None, + client_info=client_info, + ), + self.create_ad_sense_link: gapic_v1.method.wrap_method( + self.create_ad_sense_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_ad_sense_link: gapic_v1.method.wrap_method( + self.delete_ad_sense_link, + default_timeout=None, + client_info=client_info, + ), + self.list_ad_sense_links: gapic_v1.method.wrap_method( + self.list_ad_sense_links, + default_timeout=None, + client_info=client_info, + ), + self.get_event_create_rule: gapic_v1.method.wrap_method( + self.get_event_create_rule, + default_timeout=None, + client_info=client_info, + ), + self.list_event_create_rules: gapic_v1.method.wrap_method( + self.list_event_create_rules, + default_timeout=None, + client_info=client_info, + ), + self.create_event_create_rule: gapic_v1.method.wrap_method( + self.create_event_create_rule, + default_timeout=None, + client_info=client_info, + ), + self.update_event_create_rule: gapic_v1.method.wrap_method( + self.update_event_create_rule, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_create_rule: gapic_v1.method.wrap_method( + self.delete_event_create_rule, + default_timeout=None, + client_info=client_info, + ), + self.get_event_edit_rule: gapic_v1.method.wrap_method( + self.get_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.list_event_edit_rules: gapic_v1.method.wrap_method( + self.list_event_edit_rules, + default_timeout=None, + client_info=client_info, + ), + self.create_event_edit_rule: gapic_v1.method.wrap_method( + self.create_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.update_event_edit_rule: gapic_v1.method.wrap_method( + self.update_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_edit_rule: gapic_v1.method.wrap_method( + self.delete_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.reorder_event_edit_rules: gapic_v1.method.wrap_method( + self.reorder_event_edit_rules, + default_timeout=None, + client_info=client_info, + ), + self.update_data_redaction_settings: gapic_v1.method.wrap_method( + self.update_data_redaction_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_data_redaction_settings: gapic_v1.method.wrap_method( + self.get_data_redaction_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_calculated_metric: gapic_v1.method.wrap_method( + self.get_calculated_metric, + default_timeout=None, + client_info=client_info, + ), + self.create_calculated_metric: gapic_v1.method.wrap_method( + self.create_calculated_metric, + default_timeout=None, + client_info=client_info, + ), + self.list_calculated_metrics: gapic_v1.method.wrap_method( + self.list_calculated_metrics, + default_timeout=None, + client_info=client_info, + ), + self.update_calculated_metric: gapic_v1.method.wrap_method( + self.update_calculated_metric, + default_timeout=None, + client_info=client_info, + ), + self.delete_calculated_metric: gapic_v1.method.wrap_method( + self.delete_calculated_metric, + default_timeout=None, + client_info=client_info, + ), + self.create_rollup_property: gapic_v1.method.wrap_method( + self.create_rollup_property, + default_timeout=None, + client_info=client_info, + ), + self.get_rollup_property_source_link: gapic_v1.method.wrap_method( + self.get_rollup_property_source_link, + default_timeout=None, + client_info=client_info, + ), + self.list_rollup_property_source_links: gapic_v1.method.wrap_method( + self.list_rollup_property_source_links, + default_timeout=None, + client_info=client_info, + ), + self.create_rollup_property_source_link: gapic_v1.method.wrap_method( + self.create_rollup_property_source_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_rollup_property_source_link: gapic_v1.method.wrap_method( + self.delete_rollup_property_source_link, + default_timeout=None, + client_info=client_info, + ), + self.provision_subproperty: gapic_v1.method.wrap_method( + self.provision_subproperty, + default_timeout=None, + client_info=client_info, + ), + self.create_subproperty_event_filter: gapic_v1.method.wrap_method( + self.create_subproperty_event_filter, + default_timeout=None, + client_info=client_info, + ), + self.get_subproperty_event_filter: gapic_v1.method.wrap_method( + self.get_subproperty_event_filter, + default_timeout=None, + client_info=client_info, + ), + self.list_subproperty_event_filters: gapic_v1.method.wrap_method( + self.list_subproperty_event_filters, + default_timeout=None, + client_info=client_info, + ), + self.update_subproperty_event_filter: gapic_v1.method.wrap_method( + self.update_subproperty_event_filter, + default_timeout=None, + client_info=client_info, + ), + self.delete_subproperty_event_filter: gapic_v1.method.wrap_method( + self.delete_subproperty_event_filter, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_account(self) -> Callable[ + [analytics_admin.GetAccountRequest], + Union[ + resources.Account, + Awaitable[resources.Account] + ]]: + raise NotImplementedError() + + @property + def list_accounts(self) -> Callable[ + [analytics_admin.ListAccountsRequest], + Union[ + analytics_admin.ListAccountsResponse, + Awaitable[analytics_admin.ListAccountsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_account(self) -> Callable[ + [analytics_admin.DeleteAccountRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_account(self) -> Callable[ + [analytics_admin.UpdateAccountRequest], + Union[ + resources.Account, + Awaitable[resources.Account] + ]]: + raise NotImplementedError() + + @property + def provision_account_ticket(self) -> Callable[ + [analytics_admin.ProvisionAccountTicketRequest], + Union[ + analytics_admin.ProvisionAccountTicketResponse, + Awaitable[analytics_admin.ProvisionAccountTicketResponse] + ]]: + raise NotImplementedError() + + @property + def list_account_summaries(self) -> Callable[ + [analytics_admin.ListAccountSummariesRequest], + Union[ + analytics_admin.ListAccountSummariesResponse, + Awaitable[analytics_admin.ListAccountSummariesResponse] + ]]: + raise NotImplementedError() + + @property + def get_property(self) -> Callable[ + [analytics_admin.GetPropertyRequest], + Union[ + resources.Property, + Awaitable[resources.Property] + ]]: + raise NotImplementedError() + + @property + def list_properties(self) -> Callable[ + [analytics_admin.ListPropertiesRequest], + Union[ + analytics_admin.ListPropertiesResponse, + Awaitable[analytics_admin.ListPropertiesResponse] + ]]: + raise NotImplementedError() + + @property + def create_property(self) -> Callable[ + [analytics_admin.CreatePropertyRequest], + Union[ + resources.Property, + Awaitable[resources.Property] + ]]: + raise NotImplementedError() + + @property + def delete_property(self) -> Callable[ + [analytics_admin.DeletePropertyRequest], + Union[ + resources.Property, + Awaitable[resources.Property] + ]]: + raise NotImplementedError() + + @property + def update_property(self) -> Callable[ + [analytics_admin.UpdatePropertyRequest], + Union[ + resources.Property, + Awaitable[resources.Property] + ]]: + raise NotImplementedError() + + @property + def create_firebase_link(self) -> Callable[ + [analytics_admin.CreateFirebaseLinkRequest], + Union[ + resources.FirebaseLink, + Awaitable[resources.FirebaseLink] + ]]: + raise NotImplementedError() + + @property + def delete_firebase_link(self) -> Callable[ + [analytics_admin.DeleteFirebaseLinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_firebase_links(self) -> Callable[ + [analytics_admin.ListFirebaseLinksRequest], + Union[ + analytics_admin.ListFirebaseLinksResponse, + Awaitable[analytics_admin.ListFirebaseLinksResponse] + ]]: + raise NotImplementedError() + + @property + def get_global_site_tag(self) -> Callable[ + [analytics_admin.GetGlobalSiteTagRequest], + Union[ + resources.GlobalSiteTag, + Awaitable[resources.GlobalSiteTag] + ]]: + raise NotImplementedError() + + @property + def create_google_ads_link(self) -> Callable[ + [analytics_admin.CreateGoogleAdsLinkRequest], + Union[ + resources.GoogleAdsLink, + Awaitable[resources.GoogleAdsLink] + ]]: + raise NotImplementedError() + + @property + def update_google_ads_link(self) -> Callable[ + [analytics_admin.UpdateGoogleAdsLinkRequest], + Union[ + resources.GoogleAdsLink, + Awaitable[resources.GoogleAdsLink] + ]]: + raise NotImplementedError() + + @property + def delete_google_ads_link(self) -> Callable[ + [analytics_admin.DeleteGoogleAdsLinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_google_ads_links(self) -> Callable[ + [analytics_admin.ListGoogleAdsLinksRequest], + Union[ + analytics_admin.ListGoogleAdsLinksResponse, + Awaitable[analytics_admin.ListGoogleAdsLinksResponse] + ]]: + raise NotImplementedError() + + @property + def get_data_sharing_settings(self) -> Callable[ + [analytics_admin.GetDataSharingSettingsRequest], + Union[ + resources.DataSharingSettings, + Awaitable[resources.DataSharingSettings] + ]]: + raise NotImplementedError() + + @property + def get_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.GetMeasurementProtocolSecretRequest], + Union[ + resources.MeasurementProtocolSecret, + Awaitable[resources.MeasurementProtocolSecret] + ]]: + raise NotImplementedError() + + @property + def list_measurement_protocol_secrets(self) -> Callable[ + [analytics_admin.ListMeasurementProtocolSecretsRequest], + Union[ + analytics_admin.ListMeasurementProtocolSecretsResponse, + Awaitable[analytics_admin.ListMeasurementProtocolSecretsResponse] + ]]: + raise NotImplementedError() + + @property + def create_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.CreateMeasurementProtocolSecretRequest], + Union[ + resources.MeasurementProtocolSecret, + Awaitable[resources.MeasurementProtocolSecret] + ]]: + raise NotImplementedError() + + @property + def delete_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.DeleteMeasurementProtocolSecretRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.UpdateMeasurementProtocolSecretRequest], + Union[ + resources.MeasurementProtocolSecret, + Awaitable[resources.MeasurementProtocolSecret] + ]]: + raise NotImplementedError() + + @property + def acknowledge_user_data_collection(self) -> Callable[ + [analytics_admin.AcknowledgeUserDataCollectionRequest], + Union[ + analytics_admin.AcknowledgeUserDataCollectionResponse, + Awaitable[analytics_admin.AcknowledgeUserDataCollectionResponse] + ]]: + raise NotImplementedError() + + @property + def get_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.GetSKAdNetworkConversionValueSchemaRequest], + Union[ + resources.SKAdNetworkConversionValueSchema, + Awaitable[resources.SKAdNetworkConversionValueSchema] + ]]: + raise NotImplementedError() + + @property + def create_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest], + Union[ + resources.SKAdNetworkConversionValueSchema, + Awaitable[resources.SKAdNetworkConversionValueSchema] + ]]: + raise NotImplementedError() + + @property + def delete_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest], + Union[ + resources.SKAdNetworkConversionValueSchema, + Awaitable[resources.SKAdNetworkConversionValueSchema] + ]]: + raise NotImplementedError() + + @property + def list_sk_ad_network_conversion_value_schemas(self) -> Callable[ + [analytics_admin.ListSKAdNetworkConversionValueSchemasRequest], + Union[ + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse, + Awaitable[analytics_admin.ListSKAdNetworkConversionValueSchemasResponse] + ]]: + raise NotImplementedError() + + @property + def search_change_history_events(self) -> Callable[ + [analytics_admin.SearchChangeHistoryEventsRequest], + Union[ + analytics_admin.SearchChangeHistoryEventsResponse, + Awaitable[analytics_admin.SearchChangeHistoryEventsResponse] + ]]: + raise NotImplementedError() + + @property + def get_google_signals_settings(self) -> Callable[ + [analytics_admin.GetGoogleSignalsSettingsRequest], + Union[ + resources.GoogleSignalsSettings, + Awaitable[resources.GoogleSignalsSettings] + ]]: + raise NotImplementedError() + + @property + def update_google_signals_settings(self) -> Callable[ + [analytics_admin.UpdateGoogleSignalsSettingsRequest], + Union[ + resources.GoogleSignalsSettings, + Awaitable[resources.GoogleSignalsSettings] + ]]: + raise NotImplementedError() + + @property + def create_conversion_event(self) -> Callable[ + [analytics_admin.CreateConversionEventRequest], + Union[ + resources.ConversionEvent, + Awaitable[resources.ConversionEvent] + ]]: + raise NotImplementedError() + + @property + def update_conversion_event(self) -> Callable[ + [analytics_admin.UpdateConversionEventRequest], + Union[ + resources.ConversionEvent, + Awaitable[resources.ConversionEvent] + ]]: + raise NotImplementedError() + + @property + def get_conversion_event(self) -> Callable[ + [analytics_admin.GetConversionEventRequest], + Union[ + resources.ConversionEvent, + Awaitable[resources.ConversionEvent] + ]]: + raise NotImplementedError() + + @property + def delete_conversion_event(self) -> Callable[ + [analytics_admin.DeleteConversionEventRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_conversion_events(self) -> Callable[ + [analytics_admin.ListConversionEventsRequest], + Union[ + analytics_admin.ListConversionEventsResponse, + Awaitable[analytics_admin.ListConversionEventsResponse] + ]]: + raise NotImplementedError() + + @property + def create_key_event(self) -> Callable[ + [analytics_admin.CreateKeyEventRequest], + Union[ + resources.KeyEvent, + Awaitable[resources.KeyEvent] + ]]: + raise NotImplementedError() + + @property + def update_key_event(self) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], + Union[ + resources.KeyEvent, + Awaitable[resources.KeyEvent] + ]]: + raise NotImplementedError() + + @property + def get_key_event(self) -> Callable[ + [analytics_admin.GetKeyEventRequest], + Union[ + resources.KeyEvent, + Awaitable[resources.KeyEvent] + ]]: + raise NotImplementedError() + + @property + def delete_key_event(self) -> Callable[ + [analytics_admin.DeleteKeyEventRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_key_events(self) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + Union[ + analytics_admin.ListKeyEventsResponse, + Awaitable[analytics_admin.ListKeyEventsResponse] + ]]: + raise NotImplementedError() + + @property + def get_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.GetDisplayVideo360AdvertiserLinkRequest], + Union[ + resources.DisplayVideo360AdvertiserLink, + Awaitable[resources.DisplayVideo360AdvertiserLink] + ]]: + raise NotImplementedError() + + @property + def list_display_video360_advertiser_links(self) -> Callable[ + [analytics_admin.ListDisplayVideo360AdvertiserLinksRequest], + Union[ + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse, + Awaitable[analytics_admin.ListDisplayVideo360AdvertiserLinksResponse] + ]]: + raise NotImplementedError() + + @property + def create_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest], + Union[ + resources.DisplayVideo360AdvertiserLink, + Awaitable[resources.DisplayVideo360AdvertiserLink] + ]]: + raise NotImplementedError() + + @property + def delete_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest], + Union[ + resources.DisplayVideo360AdvertiserLink, + Awaitable[resources.DisplayVideo360AdvertiserLink] + ]]: + raise NotImplementedError() + + @property + def get_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest], + Union[ + resources.DisplayVideo360AdvertiserLinkProposal, + Awaitable[resources.DisplayVideo360AdvertiserLinkProposal] + ]]: + raise NotImplementedError() + + @property + def list_display_video360_advertiser_link_proposals(self) -> Callable[ + [analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest], + Union[ + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse, + Awaitable[analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse] + ]]: + raise NotImplementedError() + + @property + def create_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest], + Union[ + resources.DisplayVideo360AdvertiserLinkProposal, + Awaitable[resources.DisplayVideo360AdvertiserLinkProposal] + ]]: + raise NotImplementedError() + + @property + def delete_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def approve_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest], + Union[ + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse, + Awaitable[analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse] + ]]: + raise NotImplementedError() + + @property + def cancel_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest], + Union[ + resources.DisplayVideo360AdvertiserLinkProposal, + Awaitable[resources.DisplayVideo360AdvertiserLinkProposal] + ]]: + raise NotImplementedError() + + @property + def create_custom_dimension(self) -> Callable[ + [analytics_admin.CreateCustomDimensionRequest], + Union[ + resources.CustomDimension, + Awaitable[resources.CustomDimension] + ]]: + raise NotImplementedError() + + @property + def update_custom_dimension(self) -> Callable[ + [analytics_admin.UpdateCustomDimensionRequest], + Union[ + resources.CustomDimension, + Awaitable[resources.CustomDimension] + ]]: + raise NotImplementedError() + + @property + def list_custom_dimensions(self) -> Callable[ + [analytics_admin.ListCustomDimensionsRequest], + Union[ + analytics_admin.ListCustomDimensionsResponse, + Awaitable[analytics_admin.ListCustomDimensionsResponse] + ]]: + raise NotImplementedError() + + @property + def archive_custom_dimension(self) -> Callable[ + [analytics_admin.ArchiveCustomDimensionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_custom_dimension(self) -> Callable[ + [analytics_admin.GetCustomDimensionRequest], + Union[ + resources.CustomDimension, + Awaitable[resources.CustomDimension] + ]]: + raise NotImplementedError() + + @property + def create_custom_metric(self) -> Callable[ + [analytics_admin.CreateCustomMetricRequest], + Union[ + resources.CustomMetric, + Awaitable[resources.CustomMetric] + ]]: + raise NotImplementedError() + + @property + def update_custom_metric(self) -> Callable[ + [analytics_admin.UpdateCustomMetricRequest], + Union[ + resources.CustomMetric, + Awaitable[resources.CustomMetric] + ]]: + raise NotImplementedError() + + @property + def list_custom_metrics(self) -> Callable[ + [analytics_admin.ListCustomMetricsRequest], + Union[ + analytics_admin.ListCustomMetricsResponse, + Awaitable[analytics_admin.ListCustomMetricsResponse] + ]]: + raise NotImplementedError() + + @property + def archive_custom_metric(self) -> Callable[ + [analytics_admin.ArchiveCustomMetricRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_custom_metric(self) -> Callable[ + [analytics_admin.GetCustomMetricRequest], + Union[ + resources.CustomMetric, + Awaitable[resources.CustomMetric] + ]]: + raise NotImplementedError() + + @property + def get_data_retention_settings(self) -> Callable[ + [analytics_admin.GetDataRetentionSettingsRequest], + Union[ + resources.DataRetentionSettings, + Awaitable[resources.DataRetentionSettings] + ]]: + raise NotImplementedError() + + @property + def update_data_retention_settings(self) -> Callable[ + [analytics_admin.UpdateDataRetentionSettingsRequest], + Union[ + resources.DataRetentionSettings, + Awaitable[resources.DataRetentionSettings] + ]]: + raise NotImplementedError() + + @property + def create_data_stream(self) -> Callable[ + [analytics_admin.CreateDataStreamRequest], + Union[ + resources.DataStream, + Awaitable[resources.DataStream] + ]]: + raise NotImplementedError() + + @property + def delete_data_stream(self) -> Callable[ + [analytics_admin.DeleteDataStreamRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_data_stream(self) -> Callable[ + [analytics_admin.UpdateDataStreamRequest], + Union[ + resources.DataStream, + Awaitable[resources.DataStream] + ]]: + raise NotImplementedError() + + @property + def list_data_streams(self) -> Callable[ + [analytics_admin.ListDataStreamsRequest], + Union[ + analytics_admin.ListDataStreamsResponse, + Awaitable[analytics_admin.ListDataStreamsResponse] + ]]: + raise NotImplementedError() + + @property + def get_data_stream(self) -> Callable[ + [analytics_admin.GetDataStreamRequest], + Union[ + resources.DataStream, + Awaitable[resources.DataStream] + ]]: + raise NotImplementedError() + + @property + def get_audience(self) -> Callable[ + [analytics_admin.GetAudienceRequest], + Union[ + audience.Audience, + Awaitable[audience.Audience] + ]]: + raise NotImplementedError() + + @property + def list_audiences(self) -> Callable[ + [analytics_admin.ListAudiencesRequest], + Union[ + analytics_admin.ListAudiencesResponse, + Awaitable[analytics_admin.ListAudiencesResponse] + ]]: + raise NotImplementedError() + + @property + def create_audience(self) -> Callable[ + [analytics_admin.CreateAudienceRequest], + Union[ + gaa_audience.Audience, + Awaitable[gaa_audience.Audience] + ]]: + raise NotImplementedError() + + @property + def update_audience(self) -> Callable[ + [analytics_admin.UpdateAudienceRequest], + Union[ + gaa_audience.Audience, + Awaitable[gaa_audience.Audience] + ]]: + raise NotImplementedError() + + @property + def archive_audience(self) -> Callable[ + [analytics_admin.ArchiveAudienceRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_search_ads360_link(self) -> Callable[ + [analytics_admin.GetSearchAds360LinkRequest], + Union[ + resources.SearchAds360Link, + Awaitable[resources.SearchAds360Link] + ]]: + raise NotImplementedError() + + @property + def list_search_ads360_links(self) -> Callable[ + [analytics_admin.ListSearchAds360LinksRequest], + Union[ + analytics_admin.ListSearchAds360LinksResponse, + Awaitable[analytics_admin.ListSearchAds360LinksResponse] + ]]: + raise NotImplementedError() + + @property + def create_search_ads360_link(self) -> Callable[ + [analytics_admin.CreateSearchAds360LinkRequest], + Union[ + resources.SearchAds360Link, + Awaitable[resources.SearchAds360Link] + ]]: + raise NotImplementedError() + + @property + def delete_search_ads360_link(self) -> Callable[ + [analytics_admin.DeleteSearchAds360LinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_search_ads360_link(self) -> Callable[ + [analytics_admin.UpdateSearchAds360LinkRequest], + Union[ + resources.SearchAds360Link, + Awaitable[resources.SearchAds360Link] + ]]: + raise NotImplementedError() + + @property + def get_attribution_settings(self) -> Callable[ + [analytics_admin.GetAttributionSettingsRequest], + Union[ + resources.AttributionSettings, + Awaitable[resources.AttributionSettings] + ]]: + raise NotImplementedError() + + @property + def update_attribution_settings(self) -> Callable[ + [analytics_admin.UpdateAttributionSettingsRequest], + Union[ + resources.AttributionSettings, + Awaitable[resources.AttributionSettings] + ]]: + raise NotImplementedError() + + @property + def run_access_report(self) -> Callable[ + [analytics_admin.RunAccessReportRequest], + Union[ + analytics_admin.RunAccessReportResponse, + Awaitable[analytics_admin.RunAccessReportResponse] + ]]: + raise NotImplementedError() + + @property + def create_access_binding(self) -> Callable[ + [analytics_admin.CreateAccessBindingRequest], + Union[ + resources.AccessBinding, + Awaitable[resources.AccessBinding] + ]]: + raise NotImplementedError() + + @property + def get_access_binding(self) -> Callable[ + [analytics_admin.GetAccessBindingRequest], + Union[ + resources.AccessBinding, + Awaitable[resources.AccessBinding] + ]]: + raise NotImplementedError() + + @property + def update_access_binding(self) -> Callable[ + [analytics_admin.UpdateAccessBindingRequest], + Union[ + resources.AccessBinding, + Awaitable[resources.AccessBinding] + ]]: + raise NotImplementedError() + + @property + def delete_access_binding(self) -> Callable[ + [analytics_admin.DeleteAccessBindingRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_access_bindings(self) -> Callable[ + [analytics_admin.ListAccessBindingsRequest], + Union[ + analytics_admin.ListAccessBindingsResponse, + Awaitable[analytics_admin.ListAccessBindingsResponse] + ]]: + raise NotImplementedError() + + @property + def batch_create_access_bindings(self) -> Callable[ + [analytics_admin.BatchCreateAccessBindingsRequest], + Union[ + analytics_admin.BatchCreateAccessBindingsResponse, + Awaitable[analytics_admin.BatchCreateAccessBindingsResponse] + ]]: + raise NotImplementedError() + + @property + def batch_get_access_bindings(self) -> Callable[ + [analytics_admin.BatchGetAccessBindingsRequest], + Union[ + analytics_admin.BatchGetAccessBindingsResponse, + Awaitable[analytics_admin.BatchGetAccessBindingsResponse] + ]]: + raise NotImplementedError() + + @property + def batch_update_access_bindings(self) -> Callable[ + [analytics_admin.BatchUpdateAccessBindingsRequest], + Union[ + analytics_admin.BatchUpdateAccessBindingsResponse, + Awaitable[analytics_admin.BatchUpdateAccessBindingsResponse] + ]]: + raise NotImplementedError() + + @property + def batch_delete_access_bindings(self) -> Callable[ + [analytics_admin.BatchDeleteAccessBindingsRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_expanded_data_set(self) -> Callable[ + [analytics_admin.GetExpandedDataSetRequest], + Union[ + expanded_data_set.ExpandedDataSet, + Awaitable[expanded_data_set.ExpandedDataSet] + ]]: + raise NotImplementedError() + + @property + def list_expanded_data_sets(self) -> Callable[ + [analytics_admin.ListExpandedDataSetsRequest], + Union[ + analytics_admin.ListExpandedDataSetsResponse, + Awaitable[analytics_admin.ListExpandedDataSetsResponse] + ]]: + raise NotImplementedError() + + @property + def create_expanded_data_set(self) -> Callable[ + [analytics_admin.CreateExpandedDataSetRequest], + Union[ + gaa_expanded_data_set.ExpandedDataSet, + Awaitable[gaa_expanded_data_set.ExpandedDataSet] + ]]: + raise NotImplementedError() + + @property + def update_expanded_data_set(self) -> Callable[ + [analytics_admin.UpdateExpandedDataSetRequest], + Union[ + gaa_expanded_data_set.ExpandedDataSet, + Awaitable[gaa_expanded_data_set.ExpandedDataSet] + ]]: + raise NotImplementedError() + + @property + def delete_expanded_data_set(self) -> Callable[ + [analytics_admin.DeleteExpandedDataSetRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_channel_group(self) -> Callable[ + [analytics_admin.GetChannelGroupRequest], + Union[ + channel_group.ChannelGroup, + Awaitable[channel_group.ChannelGroup] + ]]: + raise NotImplementedError() + + @property + def list_channel_groups(self) -> Callable[ + [analytics_admin.ListChannelGroupsRequest], + Union[ + analytics_admin.ListChannelGroupsResponse, + Awaitable[analytics_admin.ListChannelGroupsResponse] + ]]: + raise NotImplementedError() + + @property + def create_channel_group(self) -> Callable[ + [analytics_admin.CreateChannelGroupRequest], + Union[ + gaa_channel_group.ChannelGroup, + Awaitable[gaa_channel_group.ChannelGroup] + ]]: + raise NotImplementedError() + + @property + def update_channel_group(self) -> Callable[ + [analytics_admin.UpdateChannelGroupRequest], + Union[ + gaa_channel_group.ChannelGroup, + Awaitable[gaa_channel_group.ChannelGroup] + ]]: + raise NotImplementedError() + + @property + def delete_channel_group(self) -> Callable[ + [analytics_admin.DeleteChannelGroupRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def set_automated_ga4_configuration_opt_out(self) -> Callable[ + [analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest], + Union[ + analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse, + Awaitable[analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse] + ]]: + raise NotImplementedError() + + @property + def fetch_automated_ga4_configuration_opt_out(self) -> Callable[ + [analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest], + Union[ + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse, + Awaitable[analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse] + ]]: + raise NotImplementedError() + + @property + def create_big_query_link(self) -> Callable[ + [analytics_admin.CreateBigQueryLinkRequest], + Union[ + resources.BigQueryLink, + Awaitable[resources.BigQueryLink] + ]]: + raise NotImplementedError() + + @property + def get_big_query_link(self) -> Callable[ + [analytics_admin.GetBigQueryLinkRequest], + Union[ + resources.BigQueryLink, + Awaitable[resources.BigQueryLink] + ]]: + raise NotImplementedError() + + @property + def list_big_query_links(self) -> Callable[ + [analytics_admin.ListBigQueryLinksRequest], + Union[ + analytics_admin.ListBigQueryLinksResponse, + Awaitable[analytics_admin.ListBigQueryLinksResponse] + ]]: + raise NotImplementedError() + + @property + def delete_big_query_link(self) -> Callable[ + [analytics_admin.DeleteBigQueryLinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_big_query_link(self) -> Callable[ + [analytics_admin.UpdateBigQueryLinkRequest], + Union[ + resources.BigQueryLink, + Awaitable[resources.BigQueryLink] + ]]: + raise NotImplementedError() + + @property + def get_enhanced_measurement_settings(self) -> Callable[ + [analytics_admin.GetEnhancedMeasurementSettingsRequest], + Union[ + resources.EnhancedMeasurementSettings, + Awaitable[resources.EnhancedMeasurementSettings] + ]]: + raise NotImplementedError() + + @property + def update_enhanced_measurement_settings(self) -> Callable[ + [analytics_admin.UpdateEnhancedMeasurementSettingsRequest], + Union[ + resources.EnhancedMeasurementSettings, + Awaitable[resources.EnhancedMeasurementSettings] + ]]: + raise NotImplementedError() + + @property + def create_connected_site_tag(self) -> Callable[ + [analytics_admin.CreateConnectedSiteTagRequest], + Union[ + analytics_admin.CreateConnectedSiteTagResponse, + Awaitable[analytics_admin.CreateConnectedSiteTagResponse] + ]]: + raise NotImplementedError() + + @property + def delete_connected_site_tag(self) -> Callable[ + [analytics_admin.DeleteConnectedSiteTagRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_connected_site_tags(self) -> Callable[ + [analytics_admin.ListConnectedSiteTagsRequest], + Union[ + analytics_admin.ListConnectedSiteTagsResponse, + Awaitable[analytics_admin.ListConnectedSiteTagsResponse] + ]]: + raise NotImplementedError() + + @property + def fetch_connected_ga4_property(self) -> Callable[ + [analytics_admin.FetchConnectedGa4PropertyRequest], + Union[ + analytics_admin.FetchConnectedGa4PropertyResponse, + Awaitable[analytics_admin.FetchConnectedGa4PropertyResponse] + ]]: + raise NotImplementedError() + + @property + def get_ad_sense_link(self) -> Callable[ + [analytics_admin.GetAdSenseLinkRequest], + Union[ + resources.AdSenseLink, + Awaitable[resources.AdSenseLink] + ]]: + raise NotImplementedError() + + @property + def create_ad_sense_link(self) -> Callable[ + [analytics_admin.CreateAdSenseLinkRequest], + Union[ + resources.AdSenseLink, + Awaitable[resources.AdSenseLink] + ]]: + raise NotImplementedError() + + @property + def delete_ad_sense_link(self) -> Callable[ + [analytics_admin.DeleteAdSenseLinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_ad_sense_links(self) -> Callable[ + [analytics_admin.ListAdSenseLinksRequest], + Union[ + analytics_admin.ListAdSenseLinksResponse, + Awaitable[analytics_admin.ListAdSenseLinksResponse] + ]]: + raise NotImplementedError() + + @property + def get_event_create_rule(self) -> Callable[ + [analytics_admin.GetEventCreateRuleRequest], + Union[ + event_create_and_edit.EventCreateRule, + Awaitable[event_create_and_edit.EventCreateRule] + ]]: + raise NotImplementedError() + + @property + def list_event_create_rules(self) -> Callable[ + [analytics_admin.ListEventCreateRulesRequest], + Union[ + analytics_admin.ListEventCreateRulesResponse, + Awaitable[analytics_admin.ListEventCreateRulesResponse] + ]]: + raise NotImplementedError() + + @property + def create_event_create_rule(self) -> Callable[ + [analytics_admin.CreateEventCreateRuleRequest], + Union[ + event_create_and_edit.EventCreateRule, + Awaitable[event_create_and_edit.EventCreateRule] + ]]: + raise NotImplementedError() + + @property + def update_event_create_rule(self) -> Callable[ + [analytics_admin.UpdateEventCreateRuleRequest], + Union[ + event_create_and_edit.EventCreateRule, + Awaitable[event_create_and_edit.EventCreateRule] + ]]: + raise NotImplementedError() + + @property + def delete_event_create_rule(self) -> Callable[ + [analytics_admin.DeleteEventCreateRuleRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_event_edit_rule(self) -> Callable[ + [analytics_admin.GetEventEditRuleRequest], + Union[ + event_create_and_edit.EventEditRule, + Awaitable[event_create_and_edit.EventEditRule] + ]]: + raise NotImplementedError() + + @property + def list_event_edit_rules(self) -> Callable[ + [analytics_admin.ListEventEditRulesRequest], + Union[ + analytics_admin.ListEventEditRulesResponse, + Awaitable[analytics_admin.ListEventEditRulesResponse] + ]]: + raise NotImplementedError() + + @property + def create_event_edit_rule(self) -> Callable[ + [analytics_admin.CreateEventEditRuleRequest], + Union[ + event_create_and_edit.EventEditRule, + Awaitable[event_create_and_edit.EventEditRule] + ]]: + raise NotImplementedError() + + @property + def update_event_edit_rule(self) -> Callable[ + [analytics_admin.UpdateEventEditRuleRequest], + Union[ + event_create_and_edit.EventEditRule, + Awaitable[event_create_and_edit.EventEditRule] + ]]: + raise NotImplementedError() + + @property + def delete_event_edit_rule(self) -> Callable[ + [analytics_admin.DeleteEventEditRuleRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def reorder_event_edit_rules(self) -> Callable[ + [analytics_admin.ReorderEventEditRulesRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_data_redaction_settings(self) -> Callable[ + [analytics_admin.UpdateDataRedactionSettingsRequest], + Union[ + resources.DataRedactionSettings, + Awaitable[resources.DataRedactionSettings] + ]]: + raise NotImplementedError() + + @property + def get_data_redaction_settings(self) -> Callable[ + [analytics_admin.GetDataRedactionSettingsRequest], + Union[ + resources.DataRedactionSettings, + Awaitable[resources.DataRedactionSettings] + ]]: + raise NotImplementedError() + + @property + def get_calculated_metric(self) -> Callable[ + [analytics_admin.GetCalculatedMetricRequest], + Union[ + resources.CalculatedMetric, + Awaitable[resources.CalculatedMetric] + ]]: + raise NotImplementedError() + + @property + def create_calculated_metric(self) -> Callable[ + [analytics_admin.CreateCalculatedMetricRequest], + Union[ + resources.CalculatedMetric, + Awaitable[resources.CalculatedMetric] + ]]: + raise NotImplementedError() + + @property + def list_calculated_metrics(self) -> Callable[ + [analytics_admin.ListCalculatedMetricsRequest], + Union[ + analytics_admin.ListCalculatedMetricsResponse, + Awaitable[analytics_admin.ListCalculatedMetricsResponse] + ]]: + raise NotImplementedError() + + @property + def update_calculated_metric(self) -> Callable[ + [analytics_admin.UpdateCalculatedMetricRequest], + Union[ + resources.CalculatedMetric, + Awaitable[resources.CalculatedMetric] + ]]: + raise NotImplementedError() + + @property + def delete_calculated_metric(self) -> Callable[ + [analytics_admin.DeleteCalculatedMetricRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def create_rollup_property(self) -> Callable[ + [analytics_admin.CreateRollupPropertyRequest], + Union[ + analytics_admin.CreateRollupPropertyResponse, + Awaitable[analytics_admin.CreateRollupPropertyResponse] + ]]: + raise NotImplementedError() + + @property + def get_rollup_property_source_link(self) -> Callable[ + [analytics_admin.GetRollupPropertySourceLinkRequest], + Union[ + resources.RollupPropertySourceLink, + Awaitable[resources.RollupPropertySourceLink] + ]]: + raise NotImplementedError() + + @property + def list_rollup_property_source_links(self) -> Callable[ + [analytics_admin.ListRollupPropertySourceLinksRequest], + Union[ + analytics_admin.ListRollupPropertySourceLinksResponse, + Awaitable[analytics_admin.ListRollupPropertySourceLinksResponse] + ]]: + raise NotImplementedError() + + @property + def create_rollup_property_source_link(self) -> Callable[ + [analytics_admin.CreateRollupPropertySourceLinkRequest], + Union[ + resources.RollupPropertySourceLink, + Awaitable[resources.RollupPropertySourceLink] + ]]: + raise NotImplementedError() + + @property + def delete_rollup_property_source_link(self) -> Callable[ + [analytics_admin.DeleteRollupPropertySourceLinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def provision_subproperty(self) -> Callable[ + [analytics_admin.ProvisionSubpropertyRequest], + Union[ + analytics_admin.ProvisionSubpropertyResponse, + Awaitable[analytics_admin.ProvisionSubpropertyResponse] + ]]: + raise NotImplementedError() + + @property + def create_subproperty_event_filter(self) -> Callable[ + [analytics_admin.CreateSubpropertyEventFilterRequest], + Union[ + gaa_subproperty_event_filter.SubpropertyEventFilter, + Awaitable[gaa_subproperty_event_filter.SubpropertyEventFilter] + ]]: + raise NotImplementedError() + + @property + def get_subproperty_event_filter(self) -> Callable[ + [analytics_admin.GetSubpropertyEventFilterRequest], + Union[ + subproperty_event_filter.SubpropertyEventFilter, + Awaitable[subproperty_event_filter.SubpropertyEventFilter] + ]]: + raise NotImplementedError() + + @property + def list_subproperty_event_filters(self) -> Callable[ + [analytics_admin.ListSubpropertyEventFiltersRequest], + Union[ + analytics_admin.ListSubpropertyEventFiltersResponse, + Awaitable[analytics_admin.ListSubpropertyEventFiltersResponse] + ]]: + raise NotImplementedError() + + @property + def update_subproperty_event_filter(self) -> Callable[ + [analytics_admin.UpdateSubpropertyEventFilterRequest], + Union[ + gaa_subproperty_event_filter.SubpropertyEventFilter, + Awaitable[gaa_subproperty_event_filter.SubpropertyEventFilter] + ]]: + raise NotImplementedError() + + @property + def delete_subproperty_event_filter(self) -> Callable[ + [analytics_admin.DeleteSubpropertyEventFilterRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AnalyticsAdminServiceTransport', +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc.py new file mode 100644 index 000000000000..36f2726f3538 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc.py @@ -0,0 +1,4331 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1alpha.types import analytics_admin +from google.analytics.admin_v1alpha.types import audience +from google.analytics.admin_v1alpha.types import audience as gaa_audience +from google.analytics.admin_v1alpha.types import channel_group +from google.analytics.admin_v1alpha.types import channel_group as gaa_channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set +from google.analytics.admin_v1alpha.types import expanded_data_set as gaa_expanded_data_set +from google.analytics.admin_v1alpha.types import resources +from google.analytics.admin_v1alpha.types import subproperty_event_filter +from google.analytics.admin_v1alpha.types import subproperty_event_filter as gaa_subproperty_event_filter +from google.protobuf import empty_pb2 # type: ignore +from .base import AnalyticsAdminServiceTransport, DEFAULT_CLIENT_INFO + + +class AnalyticsAdminServiceGrpcTransport(AnalyticsAdminServiceTransport): + """gRPC backend transport for AnalyticsAdminService. + + Service Interface for the Analytics Admin API (GA4). + + 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 = 'analyticsadmin.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'analyticsadmin.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'analyticsadmin.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 get_account(self) -> Callable[ + [analytics_admin.GetAccountRequest], + resources.Account]: + r"""Return a callable for the get account method over gRPC. + + Lookup for a single Account. + + Returns: + Callable[[~.GetAccountRequest], + ~.Account]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account' not in self._stubs: + self._stubs['get_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAccount', + request_serializer=analytics_admin.GetAccountRequest.serialize, + response_deserializer=resources.Account.deserialize, + ) + return self._stubs['get_account'] + + @property + def list_accounts(self) -> Callable[ + [analytics_admin.ListAccountsRequest], + analytics_admin.ListAccountsResponse]: + r"""Return a callable for the list accounts method over gRPC. + + Returns all accounts accessible by the caller. + + Note that these accounts might not currently have GA4 + properties. Soft-deleted (ie: "trashed") accounts are + excluded by default. Returns an empty list if no + relevant accounts are found. + + Returns: + Callable[[~.ListAccountsRequest], + ~.ListAccountsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_accounts' not in self._stubs: + self._stubs['list_accounts'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAccounts', + request_serializer=analytics_admin.ListAccountsRequest.serialize, + response_deserializer=analytics_admin.ListAccountsResponse.deserialize, + ) + return self._stubs['list_accounts'] + + @property + def delete_account(self) -> Callable[ + [analytics_admin.DeleteAccountRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete account method over gRPC. + + Marks target Account as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + accounts. However, they can be restored using the Trash + Can UI. + + If the accounts are not restored before the expiration + time, the account and all child resources (eg: + Properties, GoogleAdsLinks, Streams, AccessBindings) + will be permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found. + + Returns: + Callable[[~.DeleteAccountRequest], + ~.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_account' not in self._stubs: + self._stubs['delete_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteAccount', + request_serializer=analytics_admin.DeleteAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_account'] + + @property + def update_account(self) -> Callable[ + [analytics_admin.UpdateAccountRequest], + resources.Account]: + r"""Return a callable for the update account method over gRPC. + + Updates an account. + + Returns: + Callable[[~.UpdateAccountRequest], + ~.Account]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account' not in self._stubs: + self._stubs['update_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateAccount', + request_serializer=analytics_admin.UpdateAccountRequest.serialize, + response_deserializer=resources.Account.deserialize, + ) + return self._stubs['update_account'] + + @property + def provision_account_ticket(self) -> Callable[ + [analytics_admin.ProvisionAccountTicketRequest], + analytics_admin.ProvisionAccountTicketResponse]: + r"""Return a callable for the provision account ticket method over gRPC. + + Requests a ticket for creating an account. + + Returns: + Callable[[~.ProvisionAccountTicketRequest], + ~.ProvisionAccountTicketResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'provision_account_ticket' not in self._stubs: + self._stubs['provision_account_ticket'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ProvisionAccountTicket', + request_serializer=analytics_admin.ProvisionAccountTicketRequest.serialize, + response_deserializer=analytics_admin.ProvisionAccountTicketResponse.deserialize, + ) + return self._stubs['provision_account_ticket'] + + @property + def list_account_summaries(self) -> Callable[ + [analytics_admin.ListAccountSummariesRequest], + analytics_admin.ListAccountSummariesResponse]: + r"""Return a callable for the list account summaries method over gRPC. + + Returns summaries of all accounts accessible by the + caller. + + Returns: + Callable[[~.ListAccountSummariesRequest], + ~.ListAccountSummariesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account_summaries' not in self._stubs: + self._stubs['list_account_summaries'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAccountSummaries', + request_serializer=analytics_admin.ListAccountSummariesRequest.serialize, + response_deserializer=analytics_admin.ListAccountSummariesResponse.deserialize, + ) + return self._stubs['list_account_summaries'] + + @property + def get_property(self) -> Callable[ + [analytics_admin.GetPropertyRequest], + resources.Property]: + r"""Return a callable for the get property method over gRPC. + + Lookup for a single "GA4" Property. + + Returns: + Callable[[~.GetPropertyRequest], + ~.Property]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['get_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetProperty', + request_serializer=analytics_admin.GetPropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['get_property'] + + @property + def list_properties(self) -> Callable[ + [analytics_admin.ListPropertiesRequest], + analytics_admin.ListPropertiesResponse]: + r"""Return a callable for the list properties method over gRPC. + + Returns child Properties under the specified parent + Account. + Only "GA4" properties will be returned. + Properties will be excluded if the caller does not have + access. Soft-deleted (ie: "trashed") properties are + excluded by default. Returns an empty list if no + relevant properties are found. + + Returns: + Callable[[~.ListPropertiesRequest], + ~.ListPropertiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_properties' not in self._stubs: + self._stubs['list_properties'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListProperties', + request_serializer=analytics_admin.ListPropertiesRequest.serialize, + response_deserializer=analytics_admin.ListPropertiesResponse.deserialize, + ) + return self._stubs['list_properties'] + + @property + def create_property(self) -> Callable[ + [analytics_admin.CreatePropertyRequest], + resources.Property]: + r"""Return a callable for the create property method over gRPC. + + Creates an "GA4" property with the specified location + and attributes. + + Returns: + Callable[[~.CreatePropertyRequest], + ~.Property]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['create_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateProperty', + request_serializer=analytics_admin.CreatePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['create_property'] + + @property + def delete_property(self) -> Callable[ + [analytics_admin.DeletePropertyRequest], + resources.Property]: + r"""Return a callable for the delete property method over gRPC. + + Marks target Property as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + properties. However, they can be restored using the + Trash Can UI. + + If the properties are not restored before the expiration + time, the Property and all child resources (eg: + GoogleAdsLinks, Streams, AccessBindings) will be + permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found, or is not a + GA4 Property. + + Returns: + Callable[[~.DeletePropertyRequest], + ~.Property]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['delete_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteProperty', + request_serializer=analytics_admin.DeletePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['delete_property'] + + @property + def update_property(self) -> Callable[ + [analytics_admin.UpdatePropertyRequest], + resources.Property]: + r"""Return a callable for the update property method over gRPC. + + Updates a property. + + Returns: + Callable[[~.UpdatePropertyRequest], + ~.Property]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['update_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateProperty', + request_serializer=analytics_admin.UpdatePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['update_property'] + + @property + def create_firebase_link(self) -> Callable[ + [analytics_admin.CreateFirebaseLinkRequest], + resources.FirebaseLink]: + r"""Return a callable for the create firebase link method over gRPC. + + Creates a FirebaseLink. + + Properties can have at most one FirebaseLink. + + Returns: + Callable[[~.CreateFirebaseLinkRequest], + ~.FirebaseLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_firebase_link' not in self._stubs: + self._stubs['create_firebase_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateFirebaseLink', + request_serializer=analytics_admin.CreateFirebaseLinkRequest.serialize, + response_deserializer=resources.FirebaseLink.deserialize, + ) + return self._stubs['create_firebase_link'] + + @property + def delete_firebase_link(self) -> Callable[ + [analytics_admin.DeleteFirebaseLinkRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete firebase link method over gRPC. + + Deletes a FirebaseLink on a property + + Returns: + Callable[[~.DeleteFirebaseLinkRequest], + ~.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_firebase_link' not in self._stubs: + self._stubs['delete_firebase_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteFirebaseLink', + request_serializer=analytics_admin.DeleteFirebaseLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_firebase_link'] + + @property + def list_firebase_links(self) -> Callable[ + [analytics_admin.ListFirebaseLinksRequest], + analytics_admin.ListFirebaseLinksResponse]: + r"""Return a callable for the list firebase links method over gRPC. + + Lists FirebaseLinks on a property. + Properties can have at most one FirebaseLink. + + Returns: + Callable[[~.ListFirebaseLinksRequest], + ~.ListFirebaseLinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_firebase_links' not in self._stubs: + self._stubs['list_firebase_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListFirebaseLinks', + request_serializer=analytics_admin.ListFirebaseLinksRequest.serialize, + response_deserializer=analytics_admin.ListFirebaseLinksResponse.deserialize, + ) + return self._stubs['list_firebase_links'] + + @property + def get_global_site_tag(self) -> Callable[ + [analytics_admin.GetGlobalSiteTagRequest], + resources.GlobalSiteTag]: + r"""Return a callable for the get global site tag method over gRPC. + + Returns the Site Tag for the specified web stream. + Site Tags are immutable singletons. + + Returns: + Callable[[~.GetGlobalSiteTagRequest], + ~.GlobalSiteTag]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_global_site_tag' not in self._stubs: + self._stubs['get_global_site_tag'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetGlobalSiteTag', + request_serializer=analytics_admin.GetGlobalSiteTagRequest.serialize, + response_deserializer=resources.GlobalSiteTag.deserialize, + ) + return self._stubs['get_global_site_tag'] + + @property + def create_google_ads_link(self) -> Callable[ + [analytics_admin.CreateGoogleAdsLinkRequest], + resources.GoogleAdsLink]: + r"""Return a callable for the create google ads link method over gRPC. + + Creates a GoogleAdsLink. + + Returns: + Callable[[~.CreateGoogleAdsLinkRequest], + ~.GoogleAdsLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_link' not in self._stubs: + self._stubs['create_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateGoogleAdsLink', + request_serializer=analytics_admin.CreateGoogleAdsLinkRequest.serialize, + response_deserializer=resources.GoogleAdsLink.deserialize, + ) + return self._stubs['create_google_ads_link'] + + @property + def update_google_ads_link(self) -> Callable[ + [analytics_admin.UpdateGoogleAdsLinkRequest], + resources.GoogleAdsLink]: + r"""Return a callable for the update google ads link method over gRPC. + + Updates a GoogleAdsLink on a property + + Returns: + Callable[[~.UpdateGoogleAdsLinkRequest], + ~.GoogleAdsLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_link' not in self._stubs: + self._stubs['update_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateGoogleAdsLink', + request_serializer=analytics_admin.UpdateGoogleAdsLinkRequest.serialize, + response_deserializer=resources.GoogleAdsLink.deserialize, + ) + return self._stubs['update_google_ads_link'] + + @property + def delete_google_ads_link(self) -> Callable[ + [analytics_admin.DeleteGoogleAdsLinkRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete google ads link method over gRPC. + + Deletes a GoogleAdsLink on a property + + Returns: + Callable[[~.DeleteGoogleAdsLinkRequest], + ~.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_google_ads_link' not in self._stubs: + self._stubs['delete_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteGoogleAdsLink', + request_serializer=analytics_admin.DeleteGoogleAdsLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_google_ads_link'] + + @property + def list_google_ads_links(self) -> Callable[ + [analytics_admin.ListGoogleAdsLinksRequest], + analytics_admin.ListGoogleAdsLinksResponse]: + r"""Return a callable for the list google ads links method over gRPC. + + Lists GoogleAdsLinks on a property. + + Returns: + Callable[[~.ListGoogleAdsLinksRequest], + ~.ListGoogleAdsLinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_links' not in self._stubs: + self._stubs['list_google_ads_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListGoogleAdsLinks', + request_serializer=analytics_admin.ListGoogleAdsLinksRequest.serialize, + response_deserializer=analytics_admin.ListGoogleAdsLinksResponse.deserialize, + ) + return self._stubs['list_google_ads_links'] + + @property + def get_data_sharing_settings(self) -> Callable[ + [analytics_admin.GetDataSharingSettingsRequest], + resources.DataSharingSettings]: + r"""Return a callable for the get data sharing settings method over gRPC. + + Get data sharing settings on an account. + Data sharing settings are singletons. + + Returns: + Callable[[~.GetDataSharingSettingsRequest], + ~.DataSharingSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_sharing_settings' not in self._stubs: + self._stubs['get_data_sharing_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDataSharingSettings', + request_serializer=analytics_admin.GetDataSharingSettingsRequest.serialize, + response_deserializer=resources.DataSharingSettings.deserialize, + ) + return self._stubs['get_data_sharing_settings'] + + @property + def get_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.GetMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + r"""Return a callable for the get measurement protocol + secret method over gRPC. + + Lookup for a single "GA4" MeasurementProtocolSecret. + + Returns: + Callable[[~.GetMeasurementProtocolSecretRequest], + ~.MeasurementProtocolSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['get_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetMeasurementProtocolSecret', + request_serializer=analytics_admin.GetMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['get_measurement_protocol_secret'] + + @property + def list_measurement_protocol_secrets(self) -> Callable[ + [analytics_admin.ListMeasurementProtocolSecretsRequest], + analytics_admin.ListMeasurementProtocolSecretsResponse]: + r"""Return a callable for the list measurement protocol + secrets method over gRPC. + + Returns child MeasurementProtocolSecrets under the + specified parent Property. + + Returns: + Callable[[~.ListMeasurementProtocolSecretsRequest], + ~.ListMeasurementProtocolSecretsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secrets' not in self._stubs: + self._stubs['list_measurement_protocol_secrets'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListMeasurementProtocolSecrets', + request_serializer=analytics_admin.ListMeasurementProtocolSecretsRequest.serialize, + response_deserializer=analytics_admin.ListMeasurementProtocolSecretsResponse.deserialize, + ) + return self._stubs['list_measurement_protocol_secrets'] + + @property + def create_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.CreateMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + r"""Return a callable for the create measurement protocol + secret method over gRPC. + + Creates a measurement protocol secret. + + Returns: + Callable[[~.CreateMeasurementProtocolSecretRequest], + ~.MeasurementProtocolSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['create_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateMeasurementProtocolSecret', + request_serializer=analytics_admin.CreateMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['create_measurement_protocol_secret'] + + @property + def delete_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.DeleteMeasurementProtocolSecretRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete measurement protocol + secret method over gRPC. + + Deletes target MeasurementProtocolSecret. + + Returns: + Callable[[~.DeleteMeasurementProtocolSecretRequest], + ~.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_measurement_protocol_secret' not in self._stubs: + self._stubs['delete_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteMeasurementProtocolSecret', + request_serializer=analytics_admin.DeleteMeasurementProtocolSecretRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_measurement_protocol_secret'] + + @property + def update_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.UpdateMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + r"""Return a callable for the update measurement protocol + secret method over gRPC. + + Updates a measurement protocol secret. + + Returns: + Callable[[~.UpdateMeasurementProtocolSecretRequest], + ~.MeasurementProtocolSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['update_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateMeasurementProtocolSecret', + request_serializer=analytics_admin.UpdateMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['update_measurement_protocol_secret'] + + @property + def acknowledge_user_data_collection(self) -> Callable[ + [analytics_admin.AcknowledgeUserDataCollectionRequest], + analytics_admin.AcknowledgeUserDataCollectionResponse]: + r"""Return a callable for the acknowledge user data + collection method over gRPC. + + Acknowledges the terms of user data collection for + the specified property. + This acknowledgement must be completed (either in the + Google Analytics UI or through this API) before + MeasurementProtocolSecret resources may be created. + + Returns: + Callable[[~.AcknowledgeUserDataCollectionRequest], + ~.AcknowledgeUserDataCollectionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acknowledge_user_data_collection' not in self._stubs: + self._stubs['acknowledge_user_data_collection'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/AcknowledgeUserDataCollection', + request_serializer=analytics_admin.AcknowledgeUserDataCollectionRequest.serialize, + response_deserializer=analytics_admin.AcknowledgeUserDataCollectionResponse.deserialize, + ) + return self._stubs['acknowledge_user_data_collection'] + + @property + def get_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.GetSKAdNetworkConversionValueSchemaRequest], + resources.SKAdNetworkConversionValueSchema]: + r"""Return a callable for the get sk ad network conversion + value schema method over gRPC. + + Looks up a single SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.GetSKAdNetworkConversionValueSchemaRequest], + ~.SKAdNetworkConversionValueSchema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sk_ad_network_conversion_value_schema' not in self._stubs: + self._stubs['get_sk_ad_network_conversion_value_schema'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetSKAdNetworkConversionValueSchema', + request_serializer=analytics_admin.GetSKAdNetworkConversionValueSchemaRequest.serialize, + response_deserializer=resources.SKAdNetworkConversionValueSchema.deserialize, + ) + return self._stubs['get_sk_ad_network_conversion_value_schema'] + + @property + def create_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest], + resources.SKAdNetworkConversionValueSchema]: + r"""Return a callable for the create sk ad network + conversion value schema method over gRPC. + + Creates a SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.CreateSKAdNetworkConversionValueSchemaRequest], + ~.SKAdNetworkConversionValueSchema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sk_ad_network_conversion_value_schema' not in self._stubs: + self._stubs['create_sk_ad_network_conversion_value_schema'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateSKAdNetworkConversionValueSchema', + request_serializer=analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest.serialize, + response_deserializer=resources.SKAdNetworkConversionValueSchema.deserialize, + ) + return self._stubs['create_sk_ad_network_conversion_value_schema'] + + @property + def delete_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete sk ad network + conversion value schema method over gRPC. + + Deletes target SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.DeleteSKAdNetworkConversionValueSchemaRequest], + ~.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_sk_ad_network_conversion_value_schema' not in self._stubs: + self._stubs['delete_sk_ad_network_conversion_value_schema'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteSKAdNetworkConversionValueSchema', + request_serializer=analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_sk_ad_network_conversion_value_schema'] + + @property + def update_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest], + resources.SKAdNetworkConversionValueSchema]: + r"""Return a callable for the update sk ad network + conversion value schema method over gRPC. + + Updates a SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.UpdateSKAdNetworkConversionValueSchemaRequest], + ~.SKAdNetworkConversionValueSchema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sk_ad_network_conversion_value_schema' not in self._stubs: + self._stubs['update_sk_ad_network_conversion_value_schema'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateSKAdNetworkConversionValueSchema', + request_serializer=analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest.serialize, + response_deserializer=resources.SKAdNetworkConversionValueSchema.deserialize, + ) + return self._stubs['update_sk_ad_network_conversion_value_schema'] + + @property + def list_sk_ad_network_conversion_value_schemas(self) -> Callable[ + [analytics_admin.ListSKAdNetworkConversionValueSchemasRequest], + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse]: + r"""Return a callable for the list sk ad network conversion + value schemas method over gRPC. + + Lists SKAdNetworkConversionValueSchema on a stream. + Properties can have at most one + SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.ListSKAdNetworkConversionValueSchemasRequest], + ~.ListSKAdNetworkConversionValueSchemasResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sk_ad_network_conversion_value_schemas' not in self._stubs: + self._stubs['list_sk_ad_network_conversion_value_schemas'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListSKAdNetworkConversionValueSchemas', + request_serializer=analytics_admin.ListSKAdNetworkConversionValueSchemasRequest.serialize, + response_deserializer=analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.deserialize, + ) + return self._stubs['list_sk_ad_network_conversion_value_schemas'] + + @property + def search_change_history_events(self) -> Callable[ + [analytics_admin.SearchChangeHistoryEventsRequest], + analytics_admin.SearchChangeHistoryEventsResponse]: + r"""Return a callable for the search change history events method over gRPC. + + Searches through all changes to an account or its + children given the specified set of filters. + + Returns: + Callable[[~.SearchChangeHistoryEventsRequest], + ~.SearchChangeHistoryEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_change_history_events' not in self._stubs: + self._stubs['search_change_history_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/SearchChangeHistoryEvents', + request_serializer=analytics_admin.SearchChangeHistoryEventsRequest.serialize, + response_deserializer=analytics_admin.SearchChangeHistoryEventsResponse.deserialize, + ) + return self._stubs['search_change_history_events'] + + @property + def get_google_signals_settings(self) -> Callable[ + [analytics_admin.GetGoogleSignalsSettingsRequest], + resources.GoogleSignalsSettings]: + r"""Return a callable for the get google signals settings method over gRPC. + + Lookup for Google Signals settings for a property. + + Returns: + Callable[[~.GetGoogleSignalsSettingsRequest], + ~.GoogleSignalsSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_signals_settings' not in self._stubs: + self._stubs['get_google_signals_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetGoogleSignalsSettings', + request_serializer=analytics_admin.GetGoogleSignalsSettingsRequest.serialize, + response_deserializer=resources.GoogleSignalsSettings.deserialize, + ) + return self._stubs['get_google_signals_settings'] + + @property + def update_google_signals_settings(self) -> Callable[ + [analytics_admin.UpdateGoogleSignalsSettingsRequest], + resources.GoogleSignalsSettings]: + r"""Return a callable for the update google signals settings method over gRPC. + + Updates Google Signals settings for a property. + + Returns: + Callable[[~.UpdateGoogleSignalsSettingsRequest], + ~.GoogleSignalsSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_signals_settings' not in self._stubs: + self._stubs['update_google_signals_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateGoogleSignalsSettings', + request_serializer=analytics_admin.UpdateGoogleSignalsSettingsRequest.serialize, + response_deserializer=resources.GoogleSignalsSettings.deserialize, + ) + return self._stubs['update_google_signals_settings'] + + @property + def create_conversion_event(self) -> Callable[ + [analytics_admin.CreateConversionEventRequest], + resources.ConversionEvent]: + r"""Return a callable for the create conversion event method over gRPC. + + Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. + + Returns: + Callable[[~.CreateConversionEventRequest], + ~.ConversionEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['create_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateConversionEvent', + request_serializer=analytics_admin.CreateConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['create_conversion_event'] + + @property + def update_conversion_event(self) -> Callable[ + [analytics_admin.UpdateConversionEventRequest], + resources.ConversionEvent]: + r"""Return a callable for the update conversion event method over gRPC. + + Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. + + Returns: + Callable[[~.UpdateConversionEventRequest], + ~.ConversionEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['update_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateConversionEvent', + request_serializer=analytics_admin.UpdateConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['update_conversion_event'] + + @property + def get_conversion_event(self) -> Callable[ + [analytics_admin.GetConversionEventRequest], + resources.ConversionEvent]: + r"""Return a callable for the get conversion event method over gRPC. + + Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. + + Returns: + Callable[[~.GetConversionEventRequest], + ~.ConversionEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['get_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetConversionEvent', + request_serializer=analytics_admin.GetConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['get_conversion_event'] + + @property + def delete_conversion_event(self) -> Callable[ + [analytics_admin.DeleteConversionEventRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete conversion event method over gRPC. + + Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. + + Returns: + Callable[[~.DeleteConversionEventRequest], + ~.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_conversion_event' not in self._stubs: + self._stubs['delete_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteConversionEvent', + request_serializer=analytics_admin.DeleteConversionEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversion_event'] + + @property + def list_conversion_events(self) -> Callable[ + [analytics_admin.ListConversionEventsRequest], + analytics_admin.ListConversionEventsResponse]: + r"""Return a callable for the list conversion events method over gRPC. + + Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + + Returns an empty list if no conversion events are found. + + Returns: + Callable[[~.ListConversionEventsRequest], + ~.ListConversionEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_events' not in self._stubs: + self._stubs['list_conversion_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListConversionEvents', + request_serializer=analytics_admin.ListConversionEventsRequest.serialize, + response_deserializer=analytics_admin.ListConversionEventsResponse.deserialize, + ) + return self._stubs['list_conversion_events'] + + @property + def create_key_event(self) -> Callable[ + [analytics_admin.CreateKeyEventRequest], + resources.KeyEvent]: + r"""Return a callable for the create key event method over gRPC. + + Creates a Key Event. + + Returns: + Callable[[~.CreateKeyEventRequest], + ~.KeyEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['create_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateKeyEvent', + request_serializer=analytics_admin.CreateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['create_key_event'] + + @property + def update_key_event(self) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], + resources.KeyEvent]: + r"""Return a callable for the update key event method over gRPC. + + Updates a Key Event. + + Returns: + Callable[[~.UpdateKeyEventRequest], + ~.KeyEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['update_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateKeyEvent', + request_serializer=analytics_admin.UpdateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['update_key_event'] + + @property + def get_key_event(self) -> Callable[ + [analytics_admin.GetKeyEventRequest], + resources.KeyEvent]: + r"""Return a callable for the get key event method over gRPC. + + Retrieve a single Key Event. + + Returns: + Callable[[~.GetKeyEventRequest], + ~.KeyEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['get_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetKeyEvent', + request_serializer=analytics_admin.GetKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['get_key_event'] + + @property + def delete_key_event(self) -> Callable[ + [analytics_admin.DeleteKeyEventRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete key event method over gRPC. + + Deletes a Key Event. + + Returns: + Callable[[~.DeleteKeyEventRequest], + ~.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_key_event' not in self._stubs: + self._stubs['delete_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteKeyEvent', + request_serializer=analytics_admin.DeleteKeyEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_key_event'] + + @property + def list_key_events(self) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + analytics_admin.ListKeyEventsResponse]: + r"""Return a callable for the list key events method over gRPC. + + Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + Returns: + Callable[[~.ListKeyEventsRequest], + ~.ListKeyEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_events' not in self._stubs: + self._stubs['list_key_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListKeyEvents', + request_serializer=analytics_admin.ListKeyEventsRequest.serialize, + response_deserializer=analytics_admin.ListKeyEventsResponse.deserialize, + ) + return self._stubs['list_key_events'] + + @property + def get_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.GetDisplayVideo360AdvertiserLinkRequest], + resources.DisplayVideo360AdvertiserLink]: + r"""Return a callable for the get display video360 + advertiser link method over gRPC. + + Look up a single DisplayVideo360AdvertiserLink + + Returns: + Callable[[~.GetDisplayVideo360AdvertiserLinkRequest], + ~.DisplayVideo360AdvertiserLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link' not in self._stubs: + self._stubs['get_display_video360_advertiser_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDisplayVideo360AdvertiserLink', + request_serializer=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLink.deserialize, + ) + return self._stubs['get_display_video360_advertiser_link'] + + @property + def list_display_video360_advertiser_links(self) -> Callable[ + [analytics_admin.ListDisplayVideo360AdvertiserLinksRequest], + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse]: + r"""Return a callable for the list display video360 + advertiser links method over gRPC. + + Lists all DisplayVideo360AdvertiserLinks on a + property. + + Returns: + Callable[[~.ListDisplayVideo360AdvertiserLinksRequest], + ~.ListDisplayVideo360AdvertiserLinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_links' not in self._stubs: + self._stubs['list_display_video360_advertiser_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListDisplayVideo360AdvertiserLinks', + request_serializer=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest.serialize, + response_deserializer=analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.deserialize, + ) + return self._stubs['list_display_video360_advertiser_links'] + + @property + def create_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest], + resources.DisplayVideo360AdvertiserLink]: + r"""Return a callable for the create display video360 + advertiser link method over gRPC. + + Creates a DisplayVideo360AdvertiserLink. + This can only be utilized by users who have proper + authorization both on the Google Analytics property and + on the Display & Video 360 advertiser. Users who do not + have access to the Display & Video 360 advertiser should + instead seek to create a DisplayVideo360LinkProposal. + + Returns: + Callable[[~.CreateDisplayVideo360AdvertiserLinkRequest], + ~.DisplayVideo360AdvertiserLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link' not in self._stubs: + self._stubs['create_display_video360_advertiser_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateDisplayVideo360AdvertiserLink', + request_serializer=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLink.deserialize, + ) + return self._stubs['create_display_video360_advertiser_link'] + + @property + def delete_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete display video360 + advertiser link method over gRPC. + + Deletes a DisplayVideo360AdvertiserLink on a + property. + + Returns: + Callable[[~.DeleteDisplayVideo360AdvertiserLinkRequest], + ~.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_display_video360_advertiser_link' not in self._stubs: + self._stubs['delete_display_video360_advertiser_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteDisplayVideo360AdvertiserLink', + request_serializer=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_display_video360_advertiser_link'] + + @property + def update_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest], + resources.DisplayVideo360AdvertiserLink]: + r"""Return a callable for the update display video360 + advertiser link method over gRPC. + + Updates a DisplayVideo360AdvertiserLink on a + property. + + Returns: + Callable[[~.UpdateDisplayVideo360AdvertiserLinkRequest], + ~.DisplayVideo360AdvertiserLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link' not in self._stubs: + self._stubs['update_display_video360_advertiser_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateDisplayVideo360AdvertiserLink', + request_serializer=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLink.deserialize, + ) + return self._stubs['update_display_video360_advertiser_link'] + + @property + def get_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest], + resources.DisplayVideo360AdvertiserLinkProposal]: + r"""Return a callable for the get display video360 + advertiser link proposal method over gRPC. + + Lookup for a single + DisplayVideo360AdvertiserLinkProposal. + + Returns: + Callable[[~.GetDisplayVideo360AdvertiserLinkProposalRequest], + ~.DisplayVideo360AdvertiserLinkProposal]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['get_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLinkProposal.deserialize, + ) + return self._stubs['get_display_video360_advertiser_link_proposal'] + + @property + def list_display_video360_advertiser_link_proposals(self) -> Callable[ + [analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest], + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse]: + r"""Return a callable for the list display video360 + advertiser link proposals method over gRPC. + + Lists DisplayVideo360AdvertiserLinkProposals on a + property. + + Returns: + Callable[[~.ListDisplayVideo360AdvertiserLinkProposalsRequest], + ~.ListDisplayVideo360AdvertiserLinkProposalsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link_proposals' not in self._stubs: + self._stubs['list_display_video360_advertiser_link_proposals'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListDisplayVideo360AdvertiserLinkProposals', + request_serializer=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest.serialize, + response_deserializer=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.deserialize, + ) + return self._stubs['list_display_video360_advertiser_link_proposals'] + + @property + def create_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest], + resources.DisplayVideo360AdvertiserLinkProposal]: + r"""Return a callable for the create display video360 + advertiser link proposal method over gRPC. + + Creates a DisplayVideo360AdvertiserLinkProposal. + + Returns: + Callable[[~.CreateDisplayVideo360AdvertiserLinkProposalRequest], + ~.DisplayVideo360AdvertiserLinkProposal]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['create_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLinkProposal.deserialize, + ) + return self._stubs['create_display_video360_advertiser_link_proposal'] + + @property + def delete_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete display video360 + advertiser link proposal method over gRPC. + + Deletes a DisplayVideo360AdvertiserLinkProposal on a + property. This can only be used on cancelled proposals. + + Returns: + Callable[[~.DeleteDisplayVideo360AdvertiserLinkProposalRequest], + ~.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_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['delete_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_display_video360_advertiser_link_proposal'] + + @property + def approve_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest], + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse]: + r"""Return a callable for the approve display video360 + advertiser link proposal method over gRPC. + + Approves a DisplayVideo360AdvertiserLinkProposal. + The DisplayVideo360AdvertiserLinkProposal will be + deleted and a new DisplayVideo360AdvertiserLink will be + created. + + Returns: + Callable[[~.ApproveDisplayVideo360AdvertiserLinkProposalRequest], + ~.ApproveDisplayVideo360AdvertiserLinkProposalResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'approve_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['approve_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ApproveDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.deserialize, + ) + return self._stubs['approve_display_video360_advertiser_link_proposal'] + + @property + def cancel_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest], + resources.DisplayVideo360AdvertiserLinkProposal]: + r"""Return a callable for the cancel display video360 + advertiser link proposal method over gRPC. + + Cancels a DisplayVideo360AdvertiserLinkProposal. + Cancelling can mean either: + + - Declining a proposal initiated from Display & Video + 360 + - Withdrawing a proposal initiated from Google Analytics + After being cancelled, a proposal will eventually be + deleted automatically. + + Returns: + Callable[[~.CancelDisplayVideo360AdvertiserLinkProposalRequest], + ~.DisplayVideo360AdvertiserLinkProposal]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'cancel_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['cancel_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CancelDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLinkProposal.deserialize, + ) + return self._stubs['cancel_display_video360_advertiser_link_proposal'] + + @property + def create_custom_dimension(self) -> Callable[ + [analytics_admin.CreateCustomDimensionRequest], + resources.CustomDimension]: + r"""Return a callable for the create custom dimension method over gRPC. + + Creates a CustomDimension. + + Returns: + Callable[[~.CreateCustomDimensionRequest], + ~.CustomDimension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['create_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateCustomDimension', + request_serializer=analytics_admin.CreateCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['create_custom_dimension'] + + @property + def update_custom_dimension(self) -> Callable[ + [analytics_admin.UpdateCustomDimensionRequest], + resources.CustomDimension]: + r"""Return a callable for the update custom dimension method over gRPC. + + Updates a CustomDimension on a property. + + Returns: + Callable[[~.UpdateCustomDimensionRequest], + ~.CustomDimension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['update_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateCustomDimension', + request_serializer=analytics_admin.UpdateCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['update_custom_dimension'] + + @property + def list_custom_dimensions(self) -> Callable[ + [analytics_admin.ListCustomDimensionsRequest], + analytics_admin.ListCustomDimensionsResponse]: + r"""Return a callable for the list custom dimensions method over gRPC. + + Lists CustomDimensions on a property. + + Returns: + Callable[[~.ListCustomDimensionsRequest], + ~.ListCustomDimensionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimensions' not in self._stubs: + self._stubs['list_custom_dimensions'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListCustomDimensions', + request_serializer=analytics_admin.ListCustomDimensionsRequest.serialize, + response_deserializer=analytics_admin.ListCustomDimensionsResponse.deserialize, + ) + return self._stubs['list_custom_dimensions'] + + @property + def archive_custom_dimension(self) -> Callable[ + [analytics_admin.ArchiveCustomDimensionRequest], + empty_pb2.Empty]: + r"""Return a callable for the archive custom dimension method over gRPC. + + Archives a CustomDimension on a property. + + Returns: + Callable[[~.ArchiveCustomDimensionRequest], + ~.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 'archive_custom_dimension' not in self._stubs: + self._stubs['archive_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ArchiveCustomDimension', + request_serializer=analytics_admin.ArchiveCustomDimensionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_custom_dimension'] + + @property + def get_custom_dimension(self) -> Callable[ + [analytics_admin.GetCustomDimensionRequest], + resources.CustomDimension]: + r"""Return a callable for the get custom dimension method over gRPC. + + Lookup for a single CustomDimension. + + Returns: + Callable[[~.GetCustomDimensionRequest], + ~.CustomDimension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['get_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetCustomDimension', + request_serializer=analytics_admin.GetCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['get_custom_dimension'] + + @property + def create_custom_metric(self) -> Callable[ + [analytics_admin.CreateCustomMetricRequest], + resources.CustomMetric]: + r"""Return a callable for the create custom metric method over gRPC. + + Creates a CustomMetric. + + Returns: + Callable[[~.CreateCustomMetricRequest], + ~.CustomMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['create_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateCustomMetric', + request_serializer=analytics_admin.CreateCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['create_custom_metric'] + + @property + def update_custom_metric(self) -> Callable[ + [analytics_admin.UpdateCustomMetricRequest], + resources.CustomMetric]: + r"""Return a callable for the update custom metric method over gRPC. + + Updates a CustomMetric on a property. + + Returns: + Callable[[~.UpdateCustomMetricRequest], + ~.CustomMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['update_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateCustomMetric', + request_serializer=analytics_admin.UpdateCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['update_custom_metric'] + + @property + def list_custom_metrics(self) -> Callable[ + [analytics_admin.ListCustomMetricsRequest], + analytics_admin.ListCustomMetricsResponse]: + r"""Return a callable for the list custom metrics method over gRPC. + + Lists CustomMetrics on a property. + + Returns: + Callable[[~.ListCustomMetricsRequest], + ~.ListCustomMetricsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metrics' not in self._stubs: + self._stubs['list_custom_metrics'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListCustomMetrics', + request_serializer=analytics_admin.ListCustomMetricsRequest.serialize, + response_deserializer=analytics_admin.ListCustomMetricsResponse.deserialize, + ) + return self._stubs['list_custom_metrics'] + + @property + def archive_custom_metric(self) -> Callable[ + [analytics_admin.ArchiveCustomMetricRequest], + empty_pb2.Empty]: + r"""Return a callable for the archive custom metric method over gRPC. + + Archives a CustomMetric on a property. + + Returns: + Callable[[~.ArchiveCustomMetricRequest], + ~.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 'archive_custom_metric' not in self._stubs: + self._stubs['archive_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ArchiveCustomMetric', + request_serializer=analytics_admin.ArchiveCustomMetricRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_custom_metric'] + + @property + def get_custom_metric(self) -> Callable[ + [analytics_admin.GetCustomMetricRequest], + resources.CustomMetric]: + r"""Return a callable for the get custom metric method over gRPC. + + Lookup for a single CustomMetric. + + Returns: + Callable[[~.GetCustomMetricRequest], + ~.CustomMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['get_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetCustomMetric', + request_serializer=analytics_admin.GetCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['get_custom_metric'] + + @property + def get_data_retention_settings(self) -> Callable[ + [analytics_admin.GetDataRetentionSettingsRequest], + resources.DataRetentionSettings]: + r"""Return a callable for the get data retention settings method over gRPC. + + Returns the singleton data retention settings for + this property. + + Returns: + Callable[[~.GetDataRetentionSettingsRequest], + ~.DataRetentionSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_retention_settings' not in self._stubs: + self._stubs['get_data_retention_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDataRetentionSettings', + request_serializer=analytics_admin.GetDataRetentionSettingsRequest.serialize, + response_deserializer=resources.DataRetentionSettings.deserialize, + ) + return self._stubs['get_data_retention_settings'] + + @property + def update_data_retention_settings(self) -> Callable[ + [analytics_admin.UpdateDataRetentionSettingsRequest], + resources.DataRetentionSettings]: + r"""Return a callable for the update data retention settings method over gRPC. + + Updates the singleton data retention settings for + this property. + + Returns: + Callable[[~.UpdateDataRetentionSettingsRequest], + ~.DataRetentionSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_retention_settings' not in self._stubs: + self._stubs['update_data_retention_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateDataRetentionSettings', + request_serializer=analytics_admin.UpdateDataRetentionSettingsRequest.serialize, + response_deserializer=resources.DataRetentionSettings.deserialize, + ) + return self._stubs['update_data_retention_settings'] + + @property + def create_data_stream(self) -> Callable[ + [analytics_admin.CreateDataStreamRequest], + resources.DataStream]: + r"""Return a callable for the create data stream method over gRPC. + + Creates a DataStream. + + Returns: + Callable[[~.CreateDataStreamRequest], + ~.DataStream]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_data_stream' not in self._stubs: + self._stubs['create_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateDataStream', + request_serializer=analytics_admin.CreateDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['create_data_stream'] + + @property + def delete_data_stream(self) -> Callable[ + [analytics_admin.DeleteDataStreamRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete data stream method over gRPC. + + Deletes a DataStream on a property. + + Returns: + Callable[[~.DeleteDataStreamRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_data_stream' not in self._stubs: + self._stubs['delete_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteDataStream', + request_serializer=analytics_admin.DeleteDataStreamRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_stream'] + + @property + def update_data_stream(self) -> Callable[ + [analytics_admin.UpdateDataStreamRequest], + resources.DataStream]: + r"""Return a callable for the update data stream method over gRPC. + + Updates a DataStream on a property. + + Returns: + Callable[[~.UpdateDataStreamRequest], + ~.DataStream]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_stream' not in self._stubs: + self._stubs['update_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateDataStream', + request_serializer=analytics_admin.UpdateDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['update_data_stream'] + + @property + def list_data_streams(self) -> Callable[ + [analytics_admin.ListDataStreamsRequest], + analytics_admin.ListDataStreamsResponse]: + r"""Return a callable for the list data streams method over gRPC. + + Lists DataStreams on a property. + + Returns: + Callable[[~.ListDataStreamsRequest], + ~.ListDataStreamsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_data_streams' not in self._stubs: + self._stubs['list_data_streams'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListDataStreams', + request_serializer=analytics_admin.ListDataStreamsRequest.serialize, + response_deserializer=analytics_admin.ListDataStreamsResponse.deserialize, + ) + return self._stubs['list_data_streams'] + + @property + def get_data_stream(self) -> Callable[ + [analytics_admin.GetDataStreamRequest], + resources.DataStream]: + r"""Return a callable for the get data stream method over gRPC. + + Lookup for a single DataStream. + + Returns: + Callable[[~.GetDataStreamRequest], + ~.DataStream]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_stream' not in self._stubs: + self._stubs['get_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDataStream', + request_serializer=analytics_admin.GetDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['get_data_stream'] + + @property + def get_audience(self) -> Callable[ + [analytics_admin.GetAudienceRequest], + audience.Audience]: + r"""Return a callable for the get audience method over gRPC. + + Lookup for a single Audience. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. + + Returns: + Callable[[~.GetAudienceRequest], + ~.Audience]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_audience' not in self._stubs: + self._stubs['get_audience'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAudience', + request_serializer=analytics_admin.GetAudienceRequest.serialize, + response_deserializer=audience.Audience.deserialize, + ) + return self._stubs['get_audience'] + + @property + def list_audiences(self) -> Callable[ + [analytics_admin.ListAudiencesRequest], + analytics_admin.ListAudiencesResponse]: + r"""Return a callable for the list audiences method over gRPC. + + Lists Audiences on a property. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. + + Returns: + Callable[[~.ListAudiencesRequest], + ~.ListAudiencesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_audiences' not in self._stubs: + self._stubs['list_audiences'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAudiences', + request_serializer=analytics_admin.ListAudiencesRequest.serialize, + response_deserializer=analytics_admin.ListAudiencesResponse.deserialize, + ) + return self._stubs['list_audiences'] + + @property + def create_audience(self) -> Callable[ + [analytics_admin.CreateAudienceRequest], + gaa_audience.Audience]: + r"""Return a callable for the create audience method over gRPC. + + Creates an Audience. + + Returns: + Callable[[~.CreateAudienceRequest], + ~.Audience]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_audience' not in self._stubs: + self._stubs['create_audience'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateAudience', + request_serializer=analytics_admin.CreateAudienceRequest.serialize, + response_deserializer=gaa_audience.Audience.deserialize, + ) + return self._stubs['create_audience'] + + @property + def update_audience(self) -> Callable[ + [analytics_admin.UpdateAudienceRequest], + gaa_audience.Audience]: + r"""Return a callable for the update audience method over gRPC. + + Updates an Audience on a property. + + Returns: + Callable[[~.UpdateAudienceRequest], + ~.Audience]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_audience' not in self._stubs: + self._stubs['update_audience'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateAudience', + request_serializer=analytics_admin.UpdateAudienceRequest.serialize, + response_deserializer=gaa_audience.Audience.deserialize, + ) + return self._stubs['update_audience'] + + @property + def archive_audience(self) -> Callable[ + [analytics_admin.ArchiveAudienceRequest], + empty_pb2.Empty]: + r"""Return a callable for the archive audience method over gRPC. + + Archives an Audience on a property. + + Returns: + Callable[[~.ArchiveAudienceRequest], + ~.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 'archive_audience' not in self._stubs: + self._stubs['archive_audience'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ArchiveAudience', + request_serializer=analytics_admin.ArchiveAudienceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_audience'] + + @property + def get_search_ads360_link(self) -> Callable[ + [analytics_admin.GetSearchAds360LinkRequest], + resources.SearchAds360Link]: + r"""Return a callable for the get search ads360 link method over gRPC. + + Look up a single SearchAds360Link + + Returns: + Callable[[~.GetSearchAds360LinkRequest], + ~.SearchAds360Link]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_search_ads360_link' not in self._stubs: + self._stubs['get_search_ads360_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetSearchAds360Link', + request_serializer=analytics_admin.GetSearchAds360LinkRequest.serialize, + response_deserializer=resources.SearchAds360Link.deserialize, + ) + return self._stubs['get_search_ads360_link'] + + @property + def list_search_ads360_links(self) -> Callable[ + [analytics_admin.ListSearchAds360LinksRequest], + analytics_admin.ListSearchAds360LinksResponse]: + r"""Return a callable for the list search ads360 links method over gRPC. + + Lists all SearchAds360Links on a property. + + Returns: + Callable[[~.ListSearchAds360LinksRequest], + ~.ListSearchAds360LinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_search_ads360_links' not in self._stubs: + self._stubs['list_search_ads360_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListSearchAds360Links', + request_serializer=analytics_admin.ListSearchAds360LinksRequest.serialize, + response_deserializer=analytics_admin.ListSearchAds360LinksResponse.deserialize, + ) + return self._stubs['list_search_ads360_links'] + + @property + def create_search_ads360_link(self) -> Callable[ + [analytics_admin.CreateSearchAds360LinkRequest], + resources.SearchAds360Link]: + r"""Return a callable for the create search ads360 link method over gRPC. + + Creates a SearchAds360Link. + + Returns: + Callable[[~.CreateSearchAds360LinkRequest], + ~.SearchAds360Link]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_search_ads360_link' not in self._stubs: + self._stubs['create_search_ads360_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateSearchAds360Link', + request_serializer=analytics_admin.CreateSearchAds360LinkRequest.serialize, + response_deserializer=resources.SearchAds360Link.deserialize, + ) + return self._stubs['create_search_ads360_link'] + + @property + def delete_search_ads360_link(self) -> Callable[ + [analytics_admin.DeleteSearchAds360LinkRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete search ads360 link method over gRPC. + + Deletes a SearchAds360Link on a property. + + Returns: + Callable[[~.DeleteSearchAds360LinkRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_search_ads360_link' not in self._stubs: + self._stubs['delete_search_ads360_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteSearchAds360Link', + request_serializer=analytics_admin.DeleteSearchAds360LinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_search_ads360_link'] + + @property + def update_search_ads360_link(self) -> Callable[ + [analytics_admin.UpdateSearchAds360LinkRequest], + resources.SearchAds360Link]: + r"""Return a callable for the update search ads360 link method over gRPC. + + Updates a SearchAds360Link on a property. + + Returns: + Callable[[~.UpdateSearchAds360LinkRequest], + ~.SearchAds360Link]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_search_ads360_link' not in self._stubs: + self._stubs['update_search_ads360_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateSearchAds360Link', + request_serializer=analytics_admin.UpdateSearchAds360LinkRequest.serialize, + response_deserializer=resources.SearchAds360Link.deserialize, + ) + return self._stubs['update_search_ads360_link'] + + @property + def get_attribution_settings(self) -> Callable[ + [analytics_admin.GetAttributionSettingsRequest], + resources.AttributionSettings]: + r"""Return a callable for the get attribution settings method over gRPC. + + Lookup for a AttributionSettings singleton. + + Returns: + Callable[[~.GetAttributionSettingsRequest], + ~.AttributionSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attribution_settings' not in self._stubs: + self._stubs['get_attribution_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAttributionSettings', + request_serializer=analytics_admin.GetAttributionSettingsRequest.serialize, + response_deserializer=resources.AttributionSettings.deserialize, + ) + return self._stubs['get_attribution_settings'] + + @property + def update_attribution_settings(self) -> Callable[ + [analytics_admin.UpdateAttributionSettingsRequest], + resources.AttributionSettings]: + r"""Return a callable for the update attribution settings method over gRPC. + + Updates attribution settings on a property. + + Returns: + Callable[[~.UpdateAttributionSettingsRequest], + ~.AttributionSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attribution_settings' not in self._stubs: + self._stubs['update_attribution_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateAttributionSettings', + request_serializer=analytics_admin.UpdateAttributionSettingsRequest.serialize, + response_deserializer=resources.AttributionSettings.deserialize, + ) + return self._stubs['update_attribution_settings'] + + @property + def run_access_report(self) -> Callable[ + [analytics_admin.RunAccessReportRequest], + analytics_admin.RunAccessReportResponse]: + r"""Return a callable for the run access report method over gRPC. + + Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. + + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. + + Returns: + Callable[[~.RunAccessReportRequest], + ~.RunAccessReportResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_access_report' not in self._stubs: + self._stubs['run_access_report'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/RunAccessReport', + request_serializer=analytics_admin.RunAccessReportRequest.serialize, + response_deserializer=analytics_admin.RunAccessReportResponse.deserialize, + ) + return self._stubs['run_access_report'] + + @property + def create_access_binding(self) -> Callable[ + [analytics_admin.CreateAccessBindingRequest], + resources.AccessBinding]: + r"""Return a callable for the create access binding method over gRPC. + + Creates an access binding on an account or property. + + Returns: + Callable[[~.CreateAccessBindingRequest], + ~.AccessBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_access_binding' not in self._stubs: + self._stubs['create_access_binding'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateAccessBinding', + request_serializer=analytics_admin.CreateAccessBindingRequest.serialize, + response_deserializer=resources.AccessBinding.deserialize, + ) + return self._stubs['create_access_binding'] + + @property + def get_access_binding(self) -> Callable[ + [analytics_admin.GetAccessBindingRequest], + resources.AccessBinding]: + r"""Return a callable for the get access binding method over gRPC. + + Gets information about an access binding. + + Returns: + Callable[[~.GetAccessBindingRequest], + ~.AccessBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_access_binding' not in self._stubs: + self._stubs['get_access_binding'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAccessBinding', + request_serializer=analytics_admin.GetAccessBindingRequest.serialize, + response_deserializer=resources.AccessBinding.deserialize, + ) + return self._stubs['get_access_binding'] + + @property + def update_access_binding(self) -> Callable[ + [analytics_admin.UpdateAccessBindingRequest], + resources.AccessBinding]: + r"""Return a callable for the update access binding method over gRPC. + + Updates an access binding on an account or property. + + Returns: + Callable[[~.UpdateAccessBindingRequest], + ~.AccessBinding]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_access_binding' not in self._stubs: + self._stubs['update_access_binding'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateAccessBinding', + request_serializer=analytics_admin.UpdateAccessBindingRequest.serialize, + response_deserializer=resources.AccessBinding.deserialize, + ) + return self._stubs['update_access_binding'] + + @property + def delete_access_binding(self) -> Callable[ + [analytics_admin.DeleteAccessBindingRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete access binding method over gRPC. + + Deletes an access binding on an account or property. + + Returns: + Callable[[~.DeleteAccessBindingRequest], + ~.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_access_binding' not in self._stubs: + self._stubs['delete_access_binding'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteAccessBinding', + request_serializer=analytics_admin.DeleteAccessBindingRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_access_binding'] + + @property + def list_access_bindings(self) -> Callable[ + [analytics_admin.ListAccessBindingsRequest], + analytics_admin.ListAccessBindingsResponse]: + r"""Return a callable for the list access bindings method over gRPC. + + Lists all access bindings on an account or property. + + Returns: + Callable[[~.ListAccessBindingsRequest], + ~.ListAccessBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_access_bindings' not in self._stubs: + self._stubs['list_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAccessBindings', + request_serializer=analytics_admin.ListAccessBindingsRequest.serialize, + response_deserializer=analytics_admin.ListAccessBindingsResponse.deserialize, + ) + return self._stubs['list_access_bindings'] + + @property + def batch_create_access_bindings(self) -> Callable[ + [analytics_admin.BatchCreateAccessBindingsRequest], + analytics_admin.BatchCreateAccessBindingsResponse]: + r"""Return a callable for the batch create access bindings method over gRPC. + + Creates information about multiple access bindings to + an account or property. + + This method is transactional. If any AccessBinding + cannot be created, none of the AccessBindings will be + created. + + Returns: + Callable[[~.BatchCreateAccessBindingsRequest], + ~.BatchCreateAccessBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_access_bindings' not in self._stubs: + self._stubs['batch_create_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/BatchCreateAccessBindings', + request_serializer=analytics_admin.BatchCreateAccessBindingsRequest.serialize, + response_deserializer=analytics_admin.BatchCreateAccessBindingsResponse.deserialize, + ) + return self._stubs['batch_create_access_bindings'] + + @property + def batch_get_access_bindings(self) -> Callable[ + [analytics_admin.BatchGetAccessBindingsRequest], + analytics_admin.BatchGetAccessBindingsResponse]: + r"""Return a callable for the batch get access bindings method over gRPC. + + Gets information about multiple access bindings to an + account or property. + + Returns: + Callable[[~.BatchGetAccessBindingsRequest], + ~.BatchGetAccessBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_get_access_bindings' not in self._stubs: + self._stubs['batch_get_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/BatchGetAccessBindings', + request_serializer=analytics_admin.BatchGetAccessBindingsRequest.serialize, + response_deserializer=analytics_admin.BatchGetAccessBindingsResponse.deserialize, + ) + return self._stubs['batch_get_access_bindings'] + + @property + def batch_update_access_bindings(self) -> Callable[ + [analytics_admin.BatchUpdateAccessBindingsRequest], + analytics_admin.BatchUpdateAccessBindingsResponse]: + r"""Return a callable for the batch update access bindings method over gRPC. + + Updates information about multiple access bindings to + an account or property. + + Returns: + Callable[[~.BatchUpdateAccessBindingsRequest], + ~.BatchUpdateAccessBindingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_access_bindings' not in self._stubs: + self._stubs['batch_update_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/BatchUpdateAccessBindings', + request_serializer=analytics_admin.BatchUpdateAccessBindingsRequest.serialize, + response_deserializer=analytics_admin.BatchUpdateAccessBindingsResponse.deserialize, + ) + return self._stubs['batch_update_access_bindings'] + + @property + def batch_delete_access_bindings(self) -> Callable[ + [analytics_admin.BatchDeleteAccessBindingsRequest], + empty_pb2.Empty]: + r"""Return a callable for the batch delete access bindings method over gRPC. + + Deletes information about multiple users' links to an + account or property. + + Returns: + Callable[[~.BatchDeleteAccessBindingsRequest], + ~.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 'batch_delete_access_bindings' not in self._stubs: + self._stubs['batch_delete_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/BatchDeleteAccessBindings', + request_serializer=analytics_admin.BatchDeleteAccessBindingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['batch_delete_access_bindings'] + + @property + def get_expanded_data_set(self) -> Callable[ + [analytics_admin.GetExpandedDataSetRequest], + expanded_data_set.ExpandedDataSet]: + r"""Return a callable for the get expanded data set method over gRPC. + + Lookup for a single ExpandedDataSet. + + Returns: + Callable[[~.GetExpandedDataSetRequest], + ~.ExpandedDataSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_expanded_data_set' not in self._stubs: + self._stubs['get_expanded_data_set'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetExpandedDataSet', + request_serializer=analytics_admin.GetExpandedDataSetRequest.serialize, + response_deserializer=expanded_data_set.ExpandedDataSet.deserialize, + ) + return self._stubs['get_expanded_data_set'] + + @property + def list_expanded_data_sets(self) -> Callable[ + [analytics_admin.ListExpandedDataSetsRequest], + analytics_admin.ListExpandedDataSetsResponse]: + r"""Return a callable for the list expanded data sets method over gRPC. + + Lists ExpandedDataSets on a property. + + Returns: + Callable[[~.ListExpandedDataSetsRequest], + ~.ListExpandedDataSetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_expanded_data_sets' not in self._stubs: + self._stubs['list_expanded_data_sets'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListExpandedDataSets', + request_serializer=analytics_admin.ListExpandedDataSetsRequest.serialize, + response_deserializer=analytics_admin.ListExpandedDataSetsResponse.deserialize, + ) + return self._stubs['list_expanded_data_sets'] + + @property + def create_expanded_data_set(self) -> Callable[ + [analytics_admin.CreateExpandedDataSetRequest], + gaa_expanded_data_set.ExpandedDataSet]: + r"""Return a callable for the create expanded data set method over gRPC. + + Creates a ExpandedDataSet. + + Returns: + Callable[[~.CreateExpandedDataSetRequest], + ~.ExpandedDataSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_expanded_data_set' not in self._stubs: + self._stubs['create_expanded_data_set'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateExpandedDataSet', + request_serializer=analytics_admin.CreateExpandedDataSetRequest.serialize, + response_deserializer=gaa_expanded_data_set.ExpandedDataSet.deserialize, + ) + return self._stubs['create_expanded_data_set'] + + @property + def update_expanded_data_set(self) -> Callable[ + [analytics_admin.UpdateExpandedDataSetRequest], + gaa_expanded_data_set.ExpandedDataSet]: + r"""Return a callable for the update expanded data set method over gRPC. + + Updates a ExpandedDataSet on a property. + + Returns: + Callable[[~.UpdateExpandedDataSetRequest], + ~.ExpandedDataSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_expanded_data_set' not in self._stubs: + self._stubs['update_expanded_data_set'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateExpandedDataSet', + request_serializer=analytics_admin.UpdateExpandedDataSetRequest.serialize, + response_deserializer=gaa_expanded_data_set.ExpandedDataSet.deserialize, + ) + return self._stubs['update_expanded_data_set'] + + @property + def delete_expanded_data_set(self) -> Callable[ + [analytics_admin.DeleteExpandedDataSetRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete expanded data set method over gRPC. + + Deletes a ExpandedDataSet on a property. + + Returns: + Callable[[~.DeleteExpandedDataSetRequest], + ~.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_expanded_data_set' not in self._stubs: + self._stubs['delete_expanded_data_set'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteExpandedDataSet', + request_serializer=analytics_admin.DeleteExpandedDataSetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_expanded_data_set'] + + @property + def get_channel_group(self) -> Callable[ + [analytics_admin.GetChannelGroupRequest], + channel_group.ChannelGroup]: + r"""Return a callable for the get channel group method over gRPC. + + Lookup for a single ChannelGroup. + + Returns: + Callable[[~.GetChannelGroupRequest], + ~.ChannelGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel_group' not in self._stubs: + self._stubs['get_channel_group'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetChannelGroup', + request_serializer=analytics_admin.GetChannelGroupRequest.serialize, + response_deserializer=channel_group.ChannelGroup.deserialize, + ) + return self._stubs['get_channel_group'] + + @property + def list_channel_groups(self) -> Callable[ + [analytics_admin.ListChannelGroupsRequest], + analytics_admin.ListChannelGroupsResponse]: + r"""Return a callable for the list channel groups method over gRPC. + + Lists ChannelGroups on a property. + + Returns: + Callable[[~.ListChannelGroupsRequest], + ~.ListChannelGroupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel_groups' not in self._stubs: + self._stubs['list_channel_groups'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListChannelGroups', + request_serializer=analytics_admin.ListChannelGroupsRequest.serialize, + response_deserializer=analytics_admin.ListChannelGroupsResponse.deserialize, + ) + return self._stubs['list_channel_groups'] + + @property + def create_channel_group(self) -> Callable[ + [analytics_admin.CreateChannelGroupRequest], + gaa_channel_group.ChannelGroup]: + r"""Return a callable for the create channel group method over gRPC. + + Creates a ChannelGroup. + + Returns: + Callable[[~.CreateChannelGroupRequest], + ~.ChannelGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel_group' not in self._stubs: + self._stubs['create_channel_group'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateChannelGroup', + request_serializer=analytics_admin.CreateChannelGroupRequest.serialize, + response_deserializer=gaa_channel_group.ChannelGroup.deserialize, + ) + return self._stubs['create_channel_group'] + + @property + def update_channel_group(self) -> Callable[ + [analytics_admin.UpdateChannelGroupRequest], + gaa_channel_group.ChannelGroup]: + r"""Return a callable for the update channel group method over gRPC. + + Updates a ChannelGroup. + + Returns: + Callable[[~.UpdateChannelGroupRequest], + ~.ChannelGroup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel_group' not in self._stubs: + self._stubs['update_channel_group'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateChannelGroup', + request_serializer=analytics_admin.UpdateChannelGroupRequest.serialize, + response_deserializer=gaa_channel_group.ChannelGroup.deserialize, + ) + return self._stubs['update_channel_group'] + + @property + def delete_channel_group(self) -> Callable[ + [analytics_admin.DeleteChannelGroupRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete channel group method over gRPC. + + Deletes a ChannelGroup on a property. + + Returns: + Callable[[~.DeleteChannelGroupRequest], + ~.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_channel_group' not in self._stubs: + self._stubs['delete_channel_group'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteChannelGroup', + request_serializer=analytics_admin.DeleteChannelGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_channel_group'] + + @property + def set_automated_ga4_configuration_opt_out(self) -> Callable[ + [analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest], + analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse]: + r"""Return a callable for the set automated ga4 + configuration opt out method over gRPC. + + Sets the opt out status for the automated GA4 setup + process for a UA property. + Note: this has no effect on GA4 property. + + Returns: + Callable[[~.SetAutomatedGa4ConfigurationOptOutRequest], + ~.SetAutomatedGa4ConfigurationOptOutResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_automated_ga4_configuration_opt_out' not in self._stubs: + self._stubs['set_automated_ga4_configuration_opt_out'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/SetAutomatedGa4ConfigurationOptOut', + request_serializer=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest.serialize, + response_deserializer=analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.deserialize, + ) + return self._stubs['set_automated_ga4_configuration_opt_out'] + + @property + def fetch_automated_ga4_configuration_opt_out(self) -> Callable[ + [analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest], + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse]: + r"""Return a callable for the fetch automated ga4 + configuration opt out method over gRPC. + + Fetches the opt out status for the automated GA4 + setup process for a UA property. + Note: this has no effect on GA4 property. + + Returns: + Callable[[~.FetchAutomatedGa4ConfigurationOptOutRequest], + ~.FetchAutomatedGa4ConfigurationOptOutResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_automated_ga4_configuration_opt_out' not in self._stubs: + self._stubs['fetch_automated_ga4_configuration_opt_out'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/FetchAutomatedGa4ConfigurationOptOut', + request_serializer=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest.serialize, + response_deserializer=analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.deserialize, + ) + return self._stubs['fetch_automated_ga4_configuration_opt_out'] + + @property + def create_big_query_link(self) -> Callable[ + [analytics_admin.CreateBigQueryLinkRequest], + resources.BigQueryLink]: + r"""Return a callable for the create big query link method over gRPC. + + Creates a BigQueryLink. + + Returns: + Callable[[~.CreateBigQueryLinkRequest], + ~.BigQueryLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_link' not in self._stubs: + self._stubs['create_big_query_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateBigQueryLink', + request_serializer=analytics_admin.CreateBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs['create_big_query_link'] + + @property + def get_big_query_link(self) -> Callable[ + [analytics_admin.GetBigQueryLinkRequest], + resources.BigQueryLink]: + r"""Return a callable for the get big query link method over gRPC. + + Lookup for a single BigQuery Link. + + Returns: + Callable[[~.GetBigQueryLinkRequest], + ~.BigQueryLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_link' not in self._stubs: + self._stubs['get_big_query_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetBigQueryLink', + request_serializer=analytics_admin.GetBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs['get_big_query_link'] + + @property + def list_big_query_links(self) -> Callable[ + [analytics_admin.ListBigQueryLinksRequest], + analytics_admin.ListBigQueryLinksResponse]: + r"""Return a callable for the list big query links method over gRPC. + + Lists BigQuery Links on a property. + + Returns: + Callable[[~.ListBigQueryLinksRequest], + ~.ListBigQueryLinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_links' not in self._stubs: + self._stubs['list_big_query_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListBigQueryLinks', + request_serializer=analytics_admin.ListBigQueryLinksRequest.serialize, + response_deserializer=analytics_admin.ListBigQueryLinksResponse.deserialize, + ) + return self._stubs['list_big_query_links'] + + @property + def delete_big_query_link(self) -> Callable[ + [analytics_admin.DeleteBigQueryLinkRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete big query link method over gRPC. + + Deletes a BigQueryLink on a property. + + Returns: + Callable[[~.DeleteBigQueryLinkRequest], + ~.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_big_query_link' not in self._stubs: + self._stubs['delete_big_query_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteBigQueryLink', + request_serializer=analytics_admin.DeleteBigQueryLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_link'] + + @property + def update_big_query_link(self) -> Callable[ + [analytics_admin.UpdateBigQueryLinkRequest], + resources.BigQueryLink]: + r"""Return a callable for the update big query link method over gRPC. + + Updates a BigQueryLink. + + Returns: + Callable[[~.UpdateBigQueryLinkRequest], + ~.BigQueryLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_link' not in self._stubs: + self._stubs['update_big_query_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateBigQueryLink', + request_serializer=analytics_admin.UpdateBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs['update_big_query_link'] + + @property + def get_enhanced_measurement_settings(self) -> Callable[ + [analytics_admin.GetEnhancedMeasurementSettingsRequest], + resources.EnhancedMeasurementSettings]: + r"""Return a callable for the get enhanced measurement + settings method over gRPC. + + Returns the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Returns: + Callable[[~.GetEnhancedMeasurementSettingsRequest], + ~.EnhancedMeasurementSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_enhanced_measurement_settings' not in self._stubs: + self._stubs['get_enhanced_measurement_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetEnhancedMeasurementSettings', + request_serializer=analytics_admin.GetEnhancedMeasurementSettingsRequest.serialize, + response_deserializer=resources.EnhancedMeasurementSettings.deserialize, + ) + return self._stubs['get_enhanced_measurement_settings'] + + @property + def update_enhanced_measurement_settings(self) -> Callable[ + [analytics_admin.UpdateEnhancedMeasurementSettingsRequest], + resources.EnhancedMeasurementSettings]: + r"""Return a callable for the update enhanced measurement + settings method over gRPC. + + Updates the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Returns: + Callable[[~.UpdateEnhancedMeasurementSettingsRequest], + ~.EnhancedMeasurementSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_enhanced_measurement_settings' not in self._stubs: + self._stubs['update_enhanced_measurement_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateEnhancedMeasurementSettings', + request_serializer=analytics_admin.UpdateEnhancedMeasurementSettingsRequest.serialize, + response_deserializer=resources.EnhancedMeasurementSettings.deserialize, + ) + return self._stubs['update_enhanced_measurement_settings'] + + @property + def create_connected_site_tag(self) -> Callable[ + [analytics_admin.CreateConnectedSiteTagRequest], + analytics_admin.CreateConnectedSiteTagResponse]: + r"""Return a callable for the create connected site tag method over gRPC. + + Creates a connected site tag for a Universal + Analytics property. You can create a maximum of 20 + connected site tags per property. Note: This API cannot + be used on GA4 properties. + + Returns: + Callable[[~.CreateConnectedSiteTagRequest], + ~.CreateConnectedSiteTagResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connected_site_tag' not in self._stubs: + self._stubs['create_connected_site_tag'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateConnectedSiteTag', + request_serializer=analytics_admin.CreateConnectedSiteTagRequest.serialize, + response_deserializer=analytics_admin.CreateConnectedSiteTagResponse.deserialize, + ) + return self._stubs['create_connected_site_tag'] + + @property + def delete_connected_site_tag(self) -> Callable[ + [analytics_admin.DeleteConnectedSiteTagRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete connected site tag method over gRPC. + + Deletes a connected site tag for a Universal + Analytics property. Note: this has no effect on GA4 + properties. + + Returns: + Callable[[~.DeleteConnectedSiteTagRequest], + ~.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_connected_site_tag' not in self._stubs: + self._stubs['delete_connected_site_tag'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteConnectedSiteTag', + request_serializer=analytics_admin.DeleteConnectedSiteTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_connected_site_tag'] + + @property + def list_connected_site_tags(self) -> Callable[ + [analytics_admin.ListConnectedSiteTagsRequest], + analytics_admin.ListConnectedSiteTagsResponse]: + r"""Return a callable for the list connected site tags method over gRPC. + + Lists the connected site tags for a Universal + Analytics property. A maximum of 20 connected site tags + will be returned. Note: this has no effect on GA4 + property. + + Returns: + Callable[[~.ListConnectedSiteTagsRequest], + ~.ListConnectedSiteTagsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connected_site_tags' not in self._stubs: + self._stubs['list_connected_site_tags'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListConnectedSiteTags', + request_serializer=analytics_admin.ListConnectedSiteTagsRequest.serialize, + response_deserializer=analytics_admin.ListConnectedSiteTagsResponse.deserialize, + ) + return self._stubs['list_connected_site_tags'] + + @property + def fetch_connected_ga4_property(self) -> Callable[ + [analytics_admin.FetchConnectedGa4PropertyRequest], + analytics_admin.FetchConnectedGa4PropertyResponse]: + r"""Return a callable for the fetch connected ga4 property method over gRPC. + + Given a specified UA property, looks up the GA4 + property connected to it. Note: this cannot be used with + GA4 properties. + + Returns: + Callable[[~.FetchConnectedGa4PropertyRequest], + ~.FetchConnectedGa4PropertyResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_connected_ga4_property' not in self._stubs: + self._stubs['fetch_connected_ga4_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/FetchConnectedGa4Property', + request_serializer=analytics_admin.FetchConnectedGa4PropertyRequest.serialize, + response_deserializer=analytics_admin.FetchConnectedGa4PropertyResponse.deserialize, + ) + return self._stubs['fetch_connected_ga4_property'] + + @property + def get_ad_sense_link(self) -> Callable[ + [analytics_admin.GetAdSenseLinkRequest], + resources.AdSenseLink]: + r"""Return a callable for the get ad sense link method over gRPC. + + Looks up a single AdSenseLink. + + Returns: + Callable[[~.GetAdSenseLinkRequest], + ~.AdSenseLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ad_sense_link' not in self._stubs: + self._stubs['get_ad_sense_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAdSenseLink', + request_serializer=analytics_admin.GetAdSenseLinkRequest.serialize, + response_deserializer=resources.AdSenseLink.deserialize, + ) + return self._stubs['get_ad_sense_link'] + + @property + def create_ad_sense_link(self) -> Callable[ + [analytics_admin.CreateAdSenseLinkRequest], + resources.AdSenseLink]: + r"""Return a callable for the create ad sense link method over gRPC. + + Creates an AdSenseLink. + + Returns: + Callable[[~.CreateAdSenseLinkRequest], + ~.AdSenseLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ad_sense_link' not in self._stubs: + self._stubs['create_ad_sense_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateAdSenseLink', + request_serializer=analytics_admin.CreateAdSenseLinkRequest.serialize, + response_deserializer=resources.AdSenseLink.deserialize, + ) + return self._stubs['create_ad_sense_link'] + + @property + def delete_ad_sense_link(self) -> Callable[ + [analytics_admin.DeleteAdSenseLinkRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete ad sense link method over gRPC. + + Deletes an AdSenseLink. + + Returns: + Callable[[~.DeleteAdSenseLinkRequest], + ~.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_ad_sense_link' not in self._stubs: + self._stubs['delete_ad_sense_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteAdSenseLink', + request_serializer=analytics_admin.DeleteAdSenseLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_ad_sense_link'] + + @property + def list_ad_sense_links(self) -> Callable[ + [analytics_admin.ListAdSenseLinksRequest], + analytics_admin.ListAdSenseLinksResponse]: + r"""Return a callable for the list ad sense links method over gRPC. + + Lists AdSenseLinks on a property. + + Returns: + Callable[[~.ListAdSenseLinksRequest], + ~.ListAdSenseLinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ad_sense_links' not in self._stubs: + self._stubs['list_ad_sense_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAdSenseLinks', + request_serializer=analytics_admin.ListAdSenseLinksRequest.serialize, + response_deserializer=analytics_admin.ListAdSenseLinksResponse.deserialize, + ) + return self._stubs['list_ad_sense_links'] + + @property + def get_event_create_rule(self) -> Callable[ + [analytics_admin.GetEventCreateRuleRequest], + event_create_and_edit.EventCreateRule]: + r"""Return a callable for the get event create rule method over gRPC. + + Lookup for a single EventCreateRule. + + Returns: + Callable[[~.GetEventCreateRuleRequest], + ~.EventCreateRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_event_create_rule' not in self._stubs: + self._stubs['get_event_create_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetEventCreateRule', + request_serializer=analytics_admin.GetEventCreateRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventCreateRule.deserialize, + ) + return self._stubs['get_event_create_rule'] + + @property + def list_event_create_rules(self) -> Callable[ + [analytics_admin.ListEventCreateRulesRequest], + analytics_admin.ListEventCreateRulesResponse]: + r"""Return a callable for the list event create rules method over gRPC. + + Lists EventCreateRules on a web data stream. + + Returns: + Callable[[~.ListEventCreateRulesRequest], + ~.ListEventCreateRulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_create_rules' not in self._stubs: + self._stubs['list_event_create_rules'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListEventCreateRules', + request_serializer=analytics_admin.ListEventCreateRulesRequest.serialize, + response_deserializer=analytics_admin.ListEventCreateRulesResponse.deserialize, + ) + return self._stubs['list_event_create_rules'] + + @property + def create_event_create_rule(self) -> Callable[ + [analytics_admin.CreateEventCreateRuleRequest], + event_create_and_edit.EventCreateRule]: + r"""Return a callable for the create event create rule method over gRPC. + + Creates an EventCreateRule. + + Returns: + Callable[[~.CreateEventCreateRuleRequest], + ~.EventCreateRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_event_create_rule' not in self._stubs: + self._stubs['create_event_create_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateEventCreateRule', + request_serializer=analytics_admin.CreateEventCreateRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventCreateRule.deserialize, + ) + return self._stubs['create_event_create_rule'] + + @property + def update_event_create_rule(self) -> Callable[ + [analytics_admin.UpdateEventCreateRuleRequest], + event_create_and_edit.EventCreateRule]: + r"""Return a callable for the update event create rule method over gRPC. + + Updates an EventCreateRule. + + Returns: + Callable[[~.UpdateEventCreateRuleRequest], + ~.EventCreateRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_event_create_rule' not in self._stubs: + self._stubs['update_event_create_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateEventCreateRule', + request_serializer=analytics_admin.UpdateEventCreateRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventCreateRule.deserialize, + ) + return self._stubs['update_event_create_rule'] + + @property + def delete_event_create_rule(self) -> Callable[ + [analytics_admin.DeleteEventCreateRuleRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete event create rule method over gRPC. + + Deletes an EventCreateRule. + + Returns: + Callable[[~.DeleteEventCreateRuleRequest], + ~.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_event_create_rule' not in self._stubs: + self._stubs['delete_event_create_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteEventCreateRule', + request_serializer=analytics_admin.DeleteEventCreateRuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_event_create_rule'] + + @property + def get_event_edit_rule(self) -> Callable[ + [analytics_admin.GetEventEditRuleRequest], + event_create_and_edit.EventEditRule]: + r"""Return a callable for the get event edit rule method over gRPC. + + Lookup for a single EventEditRule. + + Returns: + Callable[[~.GetEventEditRuleRequest], + ~.EventEditRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_event_edit_rule' not in self._stubs: + self._stubs['get_event_edit_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetEventEditRule', + request_serializer=analytics_admin.GetEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs['get_event_edit_rule'] + + @property + def list_event_edit_rules(self) -> Callable[ + [analytics_admin.ListEventEditRulesRequest], + analytics_admin.ListEventEditRulesResponse]: + r"""Return a callable for the list event edit rules method over gRPC. + + Lists EventEditRules on a web data stream. + + Returns: + Callable[[~.ListEventEditRulesRequest], + ~.ListEventEditRulesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_edit_rules' not in self._stubs: + self._stubs['list_event_edit_rules'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListEventEditRules', + request_serializer=analytics_admin.ListEventEditRulesRequest.serialize, + response_deserializer=analytics_admin.ListEventEditRulesResponse.deserialize, + ) + return self._stubs['list_event_edit_rules'] + + @property + def create_event_edit_rule(self) -> Callable[ + [analytics_admin.CreateEventEditRuleRequest], + event_create_and_edit.EventEditRule]: + r"""Return a callable for the create event edit rule method over gRPC. + + Creates an EventEditRule. + + Returns: + Callable[[~.CreateEventEditRuleRequest], + ~.EventEditRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_event_edit_rule' not in self._stubs: + self._stubs['create_event_edit_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateEventEditRule', + request_serializer=analytics_admin.CreateEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs['create_event_edit_rule'] + + @property + def update_event_edit_rule(self) -> Callable[ + [analytics_admin.UpdateEventEditRuleRequest], + event_create_and_edit.EventEditRule]: + r"""Return a callable for the update event edit rule method over gRPC. + + Updates an EventEditRule. + + Returns: + Callable[[~.UpdateEventEditRuleRequest], + ~.EventEditRule]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_event_edit_rule' not in self._stubs: + self._stubs['update_event_edit_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateEventEditRule', + request_serializer=analytics_admin.UpdateEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs['update_event_edit_rule'] + + @property + def delete_event_edit_rule(self) -> Callable[ + [analytics_admin.DeleteEventEditRuleRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete event edit rule method over gRPC. + + Deletes an EventEditRule. + + Returns: + Callable[[~.DeleteEventEditRuleRequest], + ~.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_event_edit_rule' not in self._stubs: + self._stubs['delete_event_edit_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteEventEditRule', + request_serializer=analytics_admin.DeleteEventEditRuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_event_edit_rule'] + + @property + def reorder_event_edit_rules(self) -> Callable[ + [analytics_admin.ReorderEventEditRulesRequest], + empty_pb2.Empty]: + r"""Return a callable for the reorder event edit rules method over gRPC. + + Changes the processing order of event edit rules on + the specified stream. + + Returns: + Callable[[~.ReorderEventEditRulesRequest], + ~.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 'reorder_event_edit_rules' not in self._stubs: + self._stubs['reorder_event_edit_rules'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ReorderEventEditRules', + request_serializer=analytics_admin.ReorderEventEditRulesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['reorder_event_edit_rules'] + + @property + def update_data_redaction_settings(self) -> Callable[ + [analytics_admin.UpdateDataRedactionSettingsRequest], + resources.DataRedactionSettings]: + r"""Return a callable for the update data redaction settings method over gRPC. + + Updates a DataRedactionSettings on a property. + + Returns: + Callable[[~.UpdateDataRedactionSettingsRequest], + ~.DataRedactionSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_redaction_settings' not in self._stubs: + self._stubs['update_data_redaction_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateDataRedactionSettings', + request_serializer=analytics_admin.UpdateDataRedactionSettingsRequest.serialize, + response_deserializer=resources.DataRedactionSettings.deserialize, + ) + return self._stubs['update_data_redaction_settings'] + + @property + def get_data_redaction_settings(self) -> Callable[ + [analytics_admin.GetDataRedactionSettingsRequest], + resources.DataRedactionSettings]: + r"""Return a callable for the get data redaction settings method over gRPC. + + Lookup for a single DataRedactionSettings. + + Returns: + Callable[[~.GetDataRedactionSettingsRequest], + ~.DataRedactionSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_redaction_settings' not in self._stubs: + self._stubs['get_data_redaction_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDataRedactionSettings', + request_serializer=analytics_admin.GetDataRedactionSettingsRequest.serialize, + response_deserializer=resources.DataRedactionSettings.deserialize, + ) + return self._stubs['get_data_redaction_settings'] + + @property + def get_calculated_metric(self) -> Callable[ + [analytics_admin.GetCalculatedMetricRequest], + resources.CalculatedMetric]: + r"""Return a callable for the get calculated metric method over gRPC. + + Lookup for a single CalculatedMetric. + + Returns: + Callable[[~.GetCalculatedMetricRequest], + ~.CalculatedMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_calculated_metric' not in self._stubs: + self._stubs['get_calculated_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetCalculatedMetric', + request_serializer=analytics_admin.GetCalculatedMetricRequest.serialize, + response_deserializer=resources.CalculatedMetric.deserialize, + ) + return self._stubs['get_calculated_metric'] + + @property + def create_calculated_metric(self) -> Callable[ + [analytics_admin.CreateCalculatedMetricRequest], + resources.CalculatedMetric]: + r"""Return a callable for the create calculated metric method over gRPC. + + Creates a CalculatedMetric. + + Returns: + Callable[[~.CreateCalculatedMetricRequest], + ~.CalculatedMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_calculated_metric' not in self._stubs: + self._stubs['create_calculated_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateCalculatedMetric', + request_serializer=analytics_admin.CreateCalculatedMetricRequest.serialize, + response_deserializer=resources.CalculatedMetric.deserialize, + ) + return self._stubs['create_calculated_metric'] + + @property + def list_calculated_metrics(self) -> Callable[ + [analytics_admin.ListCalculatedMetricsRequest], + analytics_admin.ListCalculatedMetricsResponse]: + r"""Return a callable for the list calculated metrics method over gRPC. + + Lists CalculatedMetrics on a property. + + Returns: + Callable[[~.ListCalculatedMetricsRequest], + ~.ListCalculatedMetricsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_calculated_metrics' not in self._stubs: + self._stubs['list_calculated_metrics'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListCalculatedMetrics', + request_serializer=analytics_admin.ListCalculatedMetricsRequest.serialize, + response_deserializer=analytics_admin.ListCalculatedMetricsResponse.deserialize, + ) + return self._stubs['list_calculated_metrics'] + + @property + def update_calculated_metric(self) -> Callable[ + [analytics_admin.UpdateCalculatedMetricRequest], + resources.CalculatedMetric]: + r"""Return a callable for the update calculated metric method over gRPC. + + Updates a CalculatedMetric on a property. + + Returns: + Callable[[~.UpdateCalculatedMetricRequest], + ~.CalculatedMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_calculated_metric' not in self._stubs: + self._stubs['update_calculated_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateCalculatedMetric', + request_serializer=analytics_admin.UpdateCalculatedMetricRequest.serialize, + response_deserializer=resources.CalculatedMetric.deserialize, + ) + return self._stubs['update_calculated_metric'] + + @property + def delete_calculated_metric(self) -> Callable[ + [analytics_admin.DeleteCalculatedMetricRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete calculated metric method over gRPC. + + Deletes a CalculatedMetric on a property. + + Returns: + Callable[[~.DeleteCalculatedMetricRequest], + ~.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_calculated_metric' not in self._stubs: + self._stubs['delete_calculated_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteCalculatedMetric', + request_serializer=analytics_admin.DeleteCalculatedMetricRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_calculated_metric'] + + @property + def create_rollup_property(self) -> Callable[ + [analytics_admin.CreateRollupPropertyRequest], + analytics_admin.CreateRollupPropertyResponse]: + r"""Return a callable for the create rollup property method over gRPC. + + Create a roll-up property and all roll-up property + source links. + + Returns: + Callable[[~.CreateRollupPropertyRequest], + ~.CreateRollupPropertyResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_rollup_property' not in self._stubs: + self._stubs['create_rollup_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateRollupProperty', + request_serializer=analytics_admin.CreateRollupPropertyRequest.serialize, + response_deserializer=analytics_admin.CreateRollupPropertyResponse.deserialize, + ) + return self._stubs['create_rollup_property'] + + @property + def get_rollup_property_source_link(self) -> Callable[ + [analytics_admin.GetRollupPropertySourceLinkRequest], + resources.RollupPropertySourceLink]: + r"""Return a callable for the get rollup property source + link method over gRPC. + + Lookup for a single roll-up property source Link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Returns: + Callable[[~.GetRollupPropertySourceLinkRequest], + ~.RollupPropertySourceLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_rollup_property_source_link' not in self._stubs: + self._stubs['get_rollup_property_source_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetRollupPropertySourceLink', + request_serializer=analytics_admin.GetRollupPropertySourceLinkRequest.serialize, + response_deserializer=resources.RollupPropertySourceLink.deserialize, + ) + return self._stubs['get_rollup_property_source_link'] + + @property + def list_rollup_property_source_links(self) -> Callable[ + [analytics_admin.ListRollupPropertySourceLinksRequest], + analytics_admin.ListRollupPropertySourceLinksResponse]: + r"""Return a callable for the list rollup property source + links method over gRPC. + + Lists roll-up property source Links on a property. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Returns: + Callable[[~.ListRollupPropertySourceLinksRequest], + ~.ListRollupPropertySourceLinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_rollup_property_source_links' not in self._stubs: + self._stubs['list_rollup_property_source_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListRollupPropertySourceLinks', + request_serializer=analytics_admin.ListRollupPropertySourceLinksRequest.serialize, + response_deserializer=analytics_admin.ListRollupPropertySourceLinksResponse.deserialize, + ) + return self._stubs['list_rollup_property_source_links'] + + @property + def create_rollup_property_source_link(self) -> Callable[ + [analytics_admin.CreateRollupPropertySourceLinkRequest], + resources.RollupPropertySourceLink]: + r"""Return a callable for the create rollup property source + link method over gRPC. + + Creates a roll-up property source link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Returns: + Callable[[~.CreateRollupPropertySourceLinkRequest], + ~.RollupPropertySourceLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_rollup_property_source_link' not in self._stubs: + self._stubs['create_rollup_property_source_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateRollupPropertySourceLink', + request_serializer=analytics_admin.CreateRollupPropertySourceLinkRequest.serialize, + response_deserializer=resources.RollupPropertySourceLink.deserialize, + ) + return self._stubs['create_rollup_property_source_link'] + + @property + def delete_rollup_property_source_link(self) -> Callable[ + [analytics_admin.DeleteRollupPropertySourceLinkRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete rollup property source + link method over gRPC. + + Deletes a roll-up property source link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Returns: + Callable[[~.DeleteRollupPropertySourceLinkRequest], + ~.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_rollup_property_source_link' not in self._stubs: + self._stubs['delete_rollup_property_source_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteRollupPropertySourceLink', + request_serializer=analytics_admin.DeleteRollupPropertySourceLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_rollup_property_source_link'] + + @property + def provision_subproperty(self) -> Callable[ + [analytics_admin.ProvisionSubpropertyRequest], + analytics_admin.ProvisionSubpropertyResponse]: + r"""Return a callable for the provision subproperty method over gRPC. + + Create a subproperty and a subproperty event filter + that applies to the created subproperty. + + Returns: + Callable[[~.ProvisionSubpropertyRequest], + ~.ProvisionSubpropertyResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'provision_subproperty' not in self._stubs: + self._stubs['provision_subproperty'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ProvisionSubproperty', + request_serializer=analytics_admin.ProvisionSubpropertyRequest.serialize, + response_deserializer=analytics_admin.ProvisionSubpropertyResponse.deserialize, + ) + return self._stubs['provision_subproperty'] + + @property + def create_subproperty_event_filter(self) -> Callable[ + [analytics_admin.CreateSubpropertyEventFilterRequest], + gaa_subproperty_event_filter.SubpropertyEventFilter]: + r"""Return a callable for the create subproperty event + filter method over gRPC. + + Creates a subproperty Event Filter. + + Returns: + Callable[[~.CreateSubpropertyEventFilterRequest], + ~.SubpropertyEventFilter]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_subproperty_event_filter' not in self._stubs: + self._stubs['create_subproperty_event_filter'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateSubpropertyEventFilter', + request_serializer=analytics_admin.CreateSubpropertyEventFilterRequest.serialize, + response_deserializer=gaa_subproperty_event_filter.SubpropertyEventFilter.deserialize, + ) + return self._stubs['create_subproperty_event_filter'] + + @property + def get_subproperty_event_filter(self) -> Callable[ + [analytics_admin.GetSubpropertyEventFilterRequest], + subproperty_event_filter.SubpropertyEventFilter]: + r"""Return a callable for the get subproperty event filter method over gRPC. + + Lookup for a single subproperty Event Filter. + + Returns: + Callable[[~.GetSubpropertyEventFilterRequest], + ~.SubpropertyEventFilter]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_subproperty_event_filter' not in self._stubs: + self._stubs['get_subproperty_event_filter'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetSubpropertyEventFilter', + request_serializer=analytics_admin.GetSubpropertyEventFilterRequest.serialize, + response_deserializer=subproperty_event_filter.SubpropertyEventFilter.deserialize, + ) + return self._stubs['get_subproperty_event_filter'] + + @property + def list_subproperty_event_filters(self) -> Callable[ + [analytics_admin.ListSubpropertyEventFiltersRequest], + analytics_admin.ListSubpropertyEventFiltersResponse]: + r"""Return a callable for the list subproperty event filters method over gRPC. + + List all subproperty Event Filters on a property. + + Returns: + Callable[[~.ListSubpropertyEventFiltersRequest], + ~.ListSubpropertyEventFiltersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_subproperty_event_filters' not in self._stubs: + self._stubs['list_subproperty_event_filters'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListSubpropertyEventFilters', + request_serializer=analytics_admin.ListSubpropertyEventFiltersRequest.serialize, + response_deserializer=analytics_admin.ListSubpropertyEventFiltersResponse.deserialize, + ) + return self._stubs['list_subproperty_event_filters'] + + @property + def update_subproperty_event_filter(self) -> Callable[ + [analytics_admin.UpdateSubpropertyEventFilterRequest], + gaa_subproperty_event_filter.SubpropertyEventFilter]: + r"""Return a callable for the update subproperty event + filter method over gRPC. + + Updates a subproperty Event Filter. + + Returns: + Callable[[~.UpdateSubpropertyEventFilterRequest], + ~.SubpropertyEventFilter]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_subproperty_event_filter' not in self._stubs: + self._stubs['update_subproperty_event_filter'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateSubpropertyEventFilter', + request_serializer=analytics_admin.UpdateSubpropertyEventFilterRequest.serialize, + response_deserializer=gaa_subproperty_event_filter.SubpropertyEventFilter.deserialize, + ) + return self._stubs['update_subproperty_event_filter'] + + @property + def delete_subproperty_event_filter(self) -> Callable[ + [analytics_admin.DeleteSubpropertyEventFilterRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete subproperty event + filter method over gRPC. + + Deletes a subproperty event filter. + + Returns: + Callable[[~.DeleteSubpropertyEventFilterRequest], + ~.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_subproperty_event_filter' not in self._stubs: + self._stubs['delete_subproperty_event_filter'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteSubpropertyEventFilter', + request_serializer=analytics_admin.DeleteSubpropertyEventFilterRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_subproperty_event_filter'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AnalyticsAdminServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc_asyncio.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..bb77407156ca --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/grpc_asyncio.py @@ -0,0 +1,5086 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.analytics.admin_v1alpha.types import analytics_admin +from google.analytics.admin_v1alpha.types import audience +from google.analytics.admin_v1alpha.types import audience as gaa_audience +from google.analytics.admin_v1alpha.types import channel_group +from google.analytics.admin_v1alpha.types import channel_group as gaa_channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set +from google.analytics.admin_v1alpha.types import expanded_data_set as gaa_expanded_data_set +from google.analytics.admin_v1alpha.types import resources +from google.analytics.admin_v1alpha.types import subproperty_event_filter +from google.analytics.admin_v1alpha.types import subproperty_event_filter as gaa_subproperty_event_filter +from google.protobuf import empty_pb2 # type: ignore +from .base import AnalyticsAdminServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AnalyticsAdminServiceGrpcTransport + + +class AnalyticsAdminServiceGrpcAsyncIOTransport(AnalyticsAdminServiceTransport): + """gRPC AsyncIO backend transport for AnalyticsAdminService. + + Service Interface for the Analytics Admin API (GA4). + + 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 = 'analyticsadmin.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'analyticsadmin.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'analyticsadmin.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_account(self) -> Callable[ + [analytics_admin.GetAccountRequest], + Awaitable[resources.Account]]: + r"""Return a callable for the get account method over gRPC. + + Lookup for a single Account. + + Returns: + Callable[[~.GetAccountRequest], + Awaitable[~.Account]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account' not in self._stubs: + self._stubs['get_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAccount', + request_serializer=analytics_admin.GetAccountRequest.serialize, + response_deserializer=resources.Account.deserialize, + ) + return self._stubs['get_account'] + + @property + def list_accounts(self) -> Callable[ + [analytics_admin.ListAccountsRequest], + Awaitable[analytics_admin.ListAccountsResponse]]: + r"""Return a callable for the list accounts method over gRPC. + + Returns all accounts accessible by the caller. + + Note that these accounts might not currently have GA4 + properties. Soft-deleted (ie: "trashed") accounts are + excluded by default. Returns an empty list if no + relevant accounts are found. + + Returns: + Callable[[~.ListAccountsRequest], + Awaitable[~.ListAccountsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_accounts' not in self._stubs: + self._stubs['list_accounts'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAccounts', + request_serializer=analytics_admin.ListAccountsRequest.serialize, + response_deserializer=analytics_admin.ListAccountsResponse.deserialize, + ) + return self._stubs['list_accounts'] + + @property + def delete_account(self) -> Callable[ + [analytics_admin.DeleteAccountRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete account method over gRPC. + + Marks target Account as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + accounts. However, they can be restored using the Trash + Can UI. + + If the accounts are not restored before the expiration + time, the account and all child resources (eg: + Properties, GoogleAdsLinks, Streams, AccessBindings) + will be permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found. + + Returns: + Callable[[~.DeleteAccountRequest], + 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_account' not in self._stubs: + self._stubs['delete_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteAccount', + request_serializer=analytics_admin.DeleteAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_account'] + + @property + def update_account(self) -> Callable[ + [analytics_admin.UpdateAccountRequest], + Awaitable[resources.Account]]: + r"""Return a callable for the update account method over gRPC. + + Updates an account. + + Returns: + Callable[[~.UpdateAccountRequest], + Awaitable[~.Account]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account' not in self._stubs: + self._stubs['update_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateAccount', + request_serializer=analytics_admin.UpdateAccountRequest.serialize, + response_deserializer=resources.Account.deserialize, + ) + return self._stubs['update_account'] + + @property + def provision_account_ticket(self) -> Callable[ + [analytics_admin.ProvisionAccountTicketRequest], + Awaitable[analytics_admin.ProvisionAccountTicketResponse]]: + r"""Return a callable for the provision account ticket method over gRPC. + + Requests a ticket for creating an account. + + Returns: + Callable[[~.ProvisionAccountTicketRequest], + Awaitable[~.ProvisionAccountTicketResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'provision_account_ticket' not in self._stubs: + self._stubs['provision_account_ticket'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ProvisionAccountTicket', + request_serializer=analytics_admin.ProvisionAccountTicketRequest.serialize, + response_deserializer=analytics_admin.ProvisionAccountTicketResponse.deserialize, + ) + return self._stubs['provision_account_ticket'] + + @property + def list_account_summaries(self) -> Callable[ + [analytics_admin.ListAccountSummariesRequest], + Awaitable[analytics_admin.ListAccountSummariesResponse]]: + r"""Return a callable for the list account summaries method over gRPC. + + Returns summaries of all accounts accessible by the + caller. + + Returns: + Callable[[~.ListAccountSummariesRequest], + Awaitable[~.ListAccountSummariesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account_summaries' not in self._stubs: + self._stubs['list_account_summaries'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAccountSummaries', + request_serializer=analytics_admin.ListAccountSummariesRequest.serialize, + response_deserializer=analytics_admin.ListAccountSummariesResponse.deserialize, + ) + return self._stubs['list_account_summaries'] + + @property + def get_property(self) -> Callable[ + [analytics_admin.GetPropertyRequest], + Awaitable[resources.Property]]: + r"""Return a callable for the get property method over gRPC. + + Lookup for a single "GA4" Property. + + Returns: + Callable[[~.GetPropertyRequest], + Awaitable[~.Property]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['get_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetProperty', + request_serializer=analytics_admin.GetPropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['get_property'] + + @property + def list_properties(self) -> Callable[ + [analytics_admin.ListPropertiesRequest], + Awaitable[analytics_admin.ListPropertiesResponse]]: + r"""Return a callable for the list properties method over gRPC. + + Returns child Properties under the specified parent + Account. + Only "GA4" properties will be returned. + Properties will be excluded if the caller does not have + access. Soft-deleted (ie: "trashed") properties are + excluded by default. Returns an empty list if no + relevant properties are found. + + Returns: + Callable[[~.ListPropertiesRequest], + Awaitable[~.ListPropertiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_properties' not in self._stubs: + self._stubs['list_properties'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListProperties', + request_serializer=analytics_admin.ListPropertiesRequest.serialize, + response_deserializer=analytics_admin.ListPropertiesResponse.deserialize, + ) + return self._stubs['list_properties'] + + @property + def create_property(self) -> Callable[ + [analytics_admin.CreatePropertyRequest], + Awaitable[resources.Property]]: + r"""Return a callable for the create property method over gRPC. + + Creates an "GA4" property with the specified location + and attributes. + + Returns: + Callable[[~.CreatePropertyRequest], + Awaitable[~.Property]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['create_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateProperty', + request_serializer=analytics_admin.CreatePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['create_property'] + + @property + def delete_property(self) -> Callable[ + [analytics_admin.DeletePropertyRequest], + Awaitable[resources.Property]]: + r"""Return a callable for the delete property method over gRPC. + + Marks target Property as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + properties. However, they can be restored using the + Trash Can UI. + + If the properties are not restored before the expiration + time, the Property and all child resources (eg: + GoogleAdsLinks, Streams, AccessBindings) will be + permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found, or is not a + GA4 Property. + + Returns: + Callable[[~.DeletePropertyRequest], + Awaitable[~.Property]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['delete_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteProperty', + request_serializer=analytics_admin.DeletePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['delete_property'] + + @property + def update_property(self) -> Callable[ + [analytics_admin.UpdatePropertyRequest], + Awaitable[resources.Property]]: + r"""Return a callable for the update property method over gRPC. + + Updates a property. + + Returns: + Callable[[~.UpdatePropertyRequest], + Awaitable[~.Property]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['update_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateProperty', + request_serializer=analytics_admin.UpdatePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['update_property'] + + @property + def create_firebase_link(self) -> Callable[ + [analytics_admin.CreateFirebaseLinkRequest], + Awaitable[resources.FirebaseLink]]: + r"""Return a callable for the create firebase link method over gRPC. + + Creates a FirebaseLink. + + Properties can have at most one FirebaseLink. + + Returns: + Callable[[~.CreateFirebaseLinkRequest], + Awaitable[~.FirebaseLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_firebase_link' not in self._stubs: + self._stubs['create_firebase_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateFirebaseLink', + request_serializer=analytics_admin.CreateFirebaseLinkRequest.serialize, + response_deserializer=resources.FirebaseLink.deserialize, + ) + return self._stubs['create_firebase_link'] + + @property + def delete_firebase_link(self) -> Callable[ + [analytics_admin.DeleteFirebaseLinkRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete firebase link method over gRPC. + + Deletes a FirebaseLink on a property + + Returns: + Callable[[~.DeleteFirebaseLinkRequest], + 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_firebase_link' not in self._stubs: + self._stubs['delete_firebase_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteFirebaseLink', + request_serializer=analytics_admin.DeleteFirebaseLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_firebase_link'] + + @property + def list_firebase_links(self) -> Callable[ + [analytics_admin.ListFirebaseLinksRequest], + Awaitable[analytics_admin.ListFirebaseLinksResponse]]: + r"""Return a callable for the list firebase links method over gRPC. + + Lists FirebaseLinks on a property. + Properties can have at most one FirebaseLink. + + Returns: + Callable[[~.ListFirebaseLinksRequest], + Awaitable[~.ListFirebaseLinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_firebase_links' not in self._stubs: + self._stubs['list_firebase_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListFirebaseLinks', + request_serializer=analytics_admin.ListFirebaseLinksRequest.serialize, + response_deserializer=analytics_admin.ListFirebaseLinksResponse.deserialize, + ) + return self._stubs['list_firebase_links'] + + @property + def get_global_site_tag(self) -> Callable[ + [analytics_admin.GetGlobalSiteTagRequest], + Awaitable[resources.GlobalSiteTag]]: + r"""Return a callable for the get global site tag method over gRPC. + + Returns the Site Tag for the specified web stream. + Site Tags are immutable singletons. + + Returns: + Callable[[~.GetGlobalSiteTagRequest], + Awaitable[~.GlobalSiteTag]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_global_site_tag' not in self._stubs: + self._stubs['get_global_site_tag'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetGlobalSiteTag', + request_serializer=analytics_admin.GetGlobalSiteTagRequest.serialize, + response_deserializer=resources.GlobalSiteTag.deserialize, + ) + return self._stubs['get_global_site_tag'] + + @property + def create_google_ads_link(self) -> Callable[ + [analytics_admin.CreateGoogleAdsLinkRequest], + Awaitable[resources.GoogleAdsLink]]: + r"""Return a callable for the create google ads link method over gRPC. + + Creates a GoogleAdsLink. + + Returns: + Callable[[~.CreateGoogleAdsLinkRequest], + Awaitable[~.GoogleAdsLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_link' not in self._stubs: + self._stubs['create_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateGoogleAdsLink', + request_serializer=analytics_admin.CreateGoogleAdsLinkRequest.serialize, + response_deserializer=resources.GoogleAdsLink.deserialize, + ) + return self._stubs['create_google_ads_link'] + + @property + def update_google_ads_link(self) -> Callable[ + [analytics_admin.UpdateGoogleAdsLinkRequest], + Awaitable[resources.GoogleAdsLink]]: + r"""Return a callable for the update google ads link method over gRPC. + + Updates a GoogleAdsLink on a property + + Returns: + Callable[[~.UpdateGoogleAdsLinkRequest], + Awaitable[~.GoogleAdsLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_link' not in self._stubs: + self._stubs['update_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateGoogleAdsLink', + request_serializer=analytics_admin.UpdateGoogleAdsLinkRequest.serialize, + response_deserializer=resources.GoogleAdsLink.deserialize, + ) + return self._stubs['update_google_ads_link'] + + @property + def delete_google_ads_link(self) -> Callable[ + [analytics_admin.DeleteGoogleAdsLinkRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete google ads link method over gRPC. + + Deletes a GoogleAdsLink on a property + + Returns: + Callable[[~.DeleteGoogleAdsLinkRequest], + 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_google_ads_link' not in self._stubs: + self._stubs['delete_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteGoogleAdsLink', + request_serializer=analytics_admin.DeleteGoogleAdsLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_google_ads_link'] + + @property + def list_google_ads_links(self) -> Callable[ + [analytics_admin.ListGoogleAdsLinksRequest], + Awaitable[analytics_admin.ListGoogleAdsLinksResponse]]: + r"""Return a callable for the list google ads links method over gRPC. + + Lists GoogleAdsLinks on a property. + + Returns: + Callable[[~.ListGoogleAdsLinksRequest], + Awaitable[~.ListGoogleAdsLinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_links' not in self._stubs: + self._stubs['list_google_ads_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListGoogleAdsLinks', + request_serializer=analytics_admin.ListGoogleAdsLinksRequest.serialize, + response_deserializer=analytics_admin.ListGoogleAdsLinksResponse.deserialize, + ) + return self._stubs['list_google_ads_links'] + + @property + def get_data_sharing_settings(self) -> Callable[ + [analytics_admin.GetDataSharingSettingsRequest], + Awaitable[resources.DataSharingSettings]]: + r"""Return a callable for the get data sharing settings method over gRPC. + + Get data sharing settings on an account. + Data sharing settings are singletons. + + Returns: + Callable[[~.GetDataSharingSettingsRequest], + Awaitable[~.DataSharingSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_sharing_settings' not in self._stubs: + self._stubs['get_data_sharing_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDataSharingSettings', + request_serializer=analytics_admin.GetDataSharingSettingsRequest.serialize, + response_deserializer=resources.DataSharingSettings.deserialize, + ) + return self._stubs['get_data_sharing_settings'] + + @property + def get_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.GetMeasurementProtocolSecretRequest], + Awaitable[resources.MeasurementProtocolSecret]]: + r"""Return a callable for the get measurement protocol + secret method over gRPC. + + Lookup for a single "GA4" MeasurementProtocolSecret. + + Returns: + Callable[[~.GetMeasurementProtocolSecretRequest], + Awaitable[~.MeasurementProtocolSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['get_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetMeasurementProtocolSecret', + request_serializer=analytics_admin.GetMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['get_measurement_protocol_secret'] + + @property + def list_measurement_protocol_secrets(self) -> Callable[ + [analytics_admin.ListMeasurementProtocolSecretsRequest], + Awaitable[analytics_admin.ListMeasurementProtocolSecretsResponse]]: + r"""Return a callable for the list measurement protocol + secrets method over gRPC. + + Returns child MeasurementProtocolSecrets under the + specified parent Property. + + Returns: + Callable[[~.ListMeasurementProtocolSecretsRequest], + Awaitable[~.ListMeasurementProtocolSecretsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secrets' not in self._stubs: + self._stubs['list_measurement_protocol_secrets'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListMeasurementProtocolSecrets', + request_serializer=analytics_admin.ListMeasurementProtocolSecretsRequest.serialize, + response_deserializer=analytics_admin.ListMeasurementProtocolSecretsResponse.deserialize, + ) + return self._stubs['list_measurement_protocol_secrets'] + + @property + def create_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.CreateMeasurementProtocolSecretRequest], + Awaitable[resources.MeasurementProtocolSecret]]: + r"""Return a callable for the create measurement protocol + secret method over gRPC. + + Creates a measurement protocol secret. + + Returns: + Callable[[~.CreateMeasurementProtocolSecretRequest], + Awaitable[~.MeasurementProtocolSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['create_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateMeasurementProtocolSecret', + request_serializer=analytics_admin.CreateMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['create_measurement_protocol_secret'] + + @property + def delete_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.DeleteMeasurementProtocolSecretRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete measurement protocol + secret method over gRPC. + + Deletes target MeasurementProtocolSecret. + + Returns: + Callable[[~.DeleteMeasurementProtocolSecretRequest], + 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_measurement_protocol_secret' not in self._stubs: + self._stubs['delete_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteMeasurementProtocolSecret', + request_serializer=analytics_admin.DeleteMeasurementProtocolSecretRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_measurement_protocol_secret'] + + @property + def update_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.UpdateMeasurementProtocolSecretRequest], + Awaitable[resources.MeasurementProtocolSecret]]: + r"""Return a callable for the update measurement protocol + secret method over gRPC. + + Updates a measurement protocol secret. + + Returns: + Callable[[~.UpdateMeasurementProtocolSecretRequest], + Awaitable[~.MeasurementProtocolSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['update_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateMeasurementProtocolSecret', + request_serializer=analytics_admin.UpdateMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['update_measurement_protocol_secret'] + + @property + def acknowledge_user_data_collection(self) -> Callable[ + [analytics_admin.AcknowledgeUserDataCollectionRequest], + Awaitable[analytics_admin.AcknowledgeUserDataCollectionResponse]]: + r"""Return a callable for the acknowledge user data + collection method over gRPC. + + Acknowledges the terms of user data collection for + the specified property. + This acknowledgement must be completed (either in the + Google Analytics UI or through this API) before + MeasurementProtocolSecret resources may be created. + + Returns: + Callable[[~.AcknowledgeUserDataCollectionRequest], + Awaitable[~.AcknowledgeUserDataCollectionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acknowledge_user_data_collection' not in self._stubs: + self._stubs['acknowledge_user_data_collection'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/AcknowledgeUserDataCollection', + request_serializer=analytics_admin.AcknowledgeUserDataCollectionRequest.serialize, + response_deserializer=analytics_admin.AcknowledgeUserDataCollectionResponse.deserialize, + ) + return self._stubs['acknowledge_user_data_collection'] + + @property + def get_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.GetSKAdNetworkConversionValueSchemaRequest], + Awaitable[resources.SKAdNetworkConversionValueSchema]]: + r"""Return a callable for the get sk ad network conversion + value schema method over gRPC. + + Looks up a single SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.GetSKAdNetworkConversionValueSchemaRequest], + Awaitable[~.SKAdNetworkConversionValueSchema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sk_ad_network_conversion_value_schema' not in self._stubs: + self._stubs['get_sk_ad_network_conversion_value_schema'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetSKAdNetworkConversionValueSchema', + request_serializer=analytics_admin.GetSKAdNetworkConversionValueSchemaRequest.serialize, + response_deserializer=resources.SKAdNetworkConversionValueSchema.deserialize, + ) + return self._stubs['get_sk_ad_network_conversion_value_schema'] + + @property + def create_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest], + Awaitable[resources.SKAdNetworkConversionValueSchema]]: + r"""Return a callable for the create sk ad network + conversion value schema method over gRPC. + + Creates a SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.CreateSKAdNetworkConversionValueSchemaRequest], + Awaitable[~.SKAdNetworkConversionValueSchema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sk_ad_network_conversion_value_schema' not in self._stubs: + self._stubs['create_sk_ad_network_conversion_value_schema'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateSKAdNetworkConversionValueSchema', + request_serializer=analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest.serialize, + response_deserializer=resources.SKAdNetworkConversionValueSchema.deserialize, + ) + return self._stubs['create_sk_ad_network_conversion_value_schema'] + + @property + def delete_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete sk ad network + conversion value schema method over gRPC. + + Deletes target SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.DeleteSKAdNetworkConversionValueSchemaRequest], + 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_sk_ad_network_conversion_value_schema' not in self._stubs: + self._stubs['delete_sk_ad_network_conversion_value_schema'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteSKAdNetworkConversionValueSchema', + request_serializer=analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_sk_ad_network_conversion_value_schema'] + + @property + def update_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest], + Awaitable[resources.SKAdNetworkConversionValueSchema]]: + r"""Return a callable for the update sk ad network + conversion value schema method over gRPC. + + Updates a SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.UpdateSKAdNetworkConversionValueSchemaRequest], + Awaitable[~.SKAdNetworkConversionValueSchema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sk_ad_network_conversion_value_schema' not in self._stubs: + self._stubs['update_sk_ad_network_conversion_value_schema'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateSKAdNetworkConversionValueSchema', + request_serializer=analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest.serialize, + response_deserializer=resources.SKAdNetworkConversionValueSchema.deserialize, + ) + return self._stubs['update_sk_ad_network_conversion_value_schema'] + + @property + def list_sk_ad_network_conversion_value_schemas(self) -> Callable[ + [analytics_admin.ListSKAdNetworkConversionValueSchemasRequest], + Awaitable[analytics_admin.ListSKAdNetworkConversionValueSchemasResponse]]: + r"""Return a callable for the list sk ad network conversion + value schemas method over gRPC. + + Lists SKAdNetworkConversionValueSchema on a stream. + Properties can have at most one + SKAdNetworkConversionValueSchema. + + Returns: + Callable[[~.ListSKAdNetworkConversionValueSchemasRequest], + Awaitable[~.ListSKAdNetworkConversionValueSchemasResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_sk_ad_network_conversion_value_schemas' not in self._stubs: + self._stubs['list_sk_ad_network_conversion_value_schemas'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListSKAdNetworkConversionValueSchemas', + request_serializer=analytics_admin.ListSKAdNetworkConversionValueSchemasRequest.serialize, + response_deserializer=analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.deserialize, + ) + return self._stubs['list_sk_ad_network_conversion_value_schemas'] + + @property + def search_change_history_events(self) -> Callable[ + [analytics_admin.SearchChangeHistoryEventsRequest], + Awaitable[analytics_admin.SearchChangeHistoryEventsResponse]]: + r"""Return a callable for the search change history events method over gRPC. + + Searches through all changes to an account or its + children given the specified set of filters. + + Returns: + Callable[[~.SearchChangeHistoryEventsRequest], + Awaitable[~.SearchChangeHistoryEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_change_history_events' not in self._stubs: + self._stubs['search_change_history_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/SearchChangeHistoryEvents', + request_serializer=analytics_admin.SearchChangeHistoryEventsRequest.serialize, + response_deserializer=analytics_admin.SearchChangeHistoryEventsResponse.deserialize, + ) + return self._stubs['search_change_history_events'] + + @property + def get_google_signals_settings(self) -> Callable[ + [analytics_admin.GetGoogleSignalsSettingsRequest], + Awaitable[resources.GoogleSignalsSettings]]: + r"""Return a callable for the get google signals settings method over gRPC. + + Lookup for Google Signals settings for a property. + + Returns: + Callable[[~.GetGoogleSignalsSettingsRequest], + Awaitable[~.GoogleSignalsSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_signals_settings' not in self._stubs: + self._stubs['get_google_signals_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetGoogleSignalsSettings', + request_serializer=analytics_admin.GetGoogleSignalsSettingsRequest.serialize, + response_deserializer=resources.GoogleSignalsSettings.deserialize, + ) + return self._stubs['get_google_signals_settings'] + + @property + def update_google_signals_settings(self) -> Callable[ + [analytics_admin.UpdateGoogleSignalsSettingsRequest], + Awaitable[resources.GoogleSignalsSettings]]: + r"""Return a callable for the update google signals settings method over gRPC. + + Updates Google Signals settings for a property. + + Returns: + Callable[[~.UpdateGoogleSignalsSettingsRequest], + Awaitable[~.GoogleSignalsSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_signals_settings' not in self._stubs: + self._stubs['update_google_signals_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateGoogleSignalsSettings', + request_serializer=analytics_admin.UpdateGoogleSignalsSettingsRequest.serialize, + response_deserializer=resources.GoogleSignalsSettings.deserialize, + ) + return self._stubs['update_google_signals_settings'] + + @property + def create_conversion_event(self) -> Callable[ + [analytics_admin.CreateConversionEventRequest], + Awaitable[resources.ConversionEvent]]: + r"""Return a callable for the create conversion event method over gRPC. + + Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. + + Returns: + Callable[[~.CreateConversionEventRequest], + Awaitable[~.ConversionEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['create_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateConversionEvent', + request_serializer=analytics_admin.CreateConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['create_conversion_event'] + + @property + def update_conversion_event(self) -> Callable[ + [analytics_admin.UpdateConversionEventRequest], + Awaitable[resources.ConversionEvent]]: + r"""Return a callable for the update conversion event method over gRPC. + + Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. + + Returns: + Callable[[~.UpdateConversionEventRequest], + Awaitable[~.ConversionEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['update_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateConversionEvent', + request_serializer=analytics_admin.UpdateConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['update_conversion_event'] + + @property + def get_conversion_event(self) -> Callable[ + [analytics_admin.GetConversionEventRequest], + Awaitable[resources.ConversionEvent]]: + r"""Return a callable for the get conversion event method over gRPC. + + Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. + + Returns: + Callable[[~.GetConversionEventRequest], + Awaitable[~.ConversionEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['get_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetConversionEvent', + request_serializer=analytics_admin.GetConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['get_conversion_event'] + + @property + def delete_conversion_event(self) -> Callable[ + [analytics_admin.DeleteConversionEventRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete conversion event method over gRPC. + + Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. + + Returns: + Callable[[~.DeleteConversionEventRequest], + 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_conversion_event' not in self._stubs: + self._stubs['delete_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteConversionEvent', + request_serializer=analytics_admin.DeleteConversionEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversion_event'] + + @property + def list_conversion_events(self) -> Callable[ + [analytics_admin.ListConversionEventsRequest], + Awaitable[analytics_admin.ListConversionEventsResponse]]: + r"""Return a callable for the list conversion events method over gRPC. + + Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + + Returns an empty list if no conversion events are found. + + Returns: + Callable[[~.ListConversionEventsRequest], + Awaitable[~.ListConversionEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_events' not in self._stubs: + self._stubs['list_conversion_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListConversionEvents', + request_serializer=analytics_admin.ListConversionEventsRequest.serialize, + response_deserializer=analytics_admin.ListConversionEventsResponse.deserialize, + ) + return self._stubs['list_conversion_events'] + + @property + def create_key_event(self) -> Callable[ + [analytics_admin.CreateKeyEventRequest], + Awaitable[resources.KeyEvent]]: + r"""Return a callable for the create key event method over gRPC. + + Creates a Key Event. + + Returns: + Callable[[~.CreateKeyEventRequest], + Awaitable[~.KeyEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['create_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateKeyEvent', + request_serializer=analytics_admin.CreateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['create_key_event'] + + @property + def update_key_event(self) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], + Awaitable[resources.KeyEvent]]: + r"""Return a callable for the update key event method over gRPC. + + Updates a Key Event. + + Returns: + Callable[[~.UpdateKeyEventRequest], + Awaitable[~.KeyEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['update_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateKeyEvent', + request_serializer=analytics_admin.UpdateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['update_key_event'] + + @property + def get_key_event(self) -> Callable[ + [analytics_admin.GetKeyEventRequest], + Awaitable[resources.KeyEvent]]: + r"""Return a callable for the get key event method over gRPC. + + Retrieve a single Key Event. + + Returns: + Callable[[~.GetKeyEventRequest], + Awaitable[~.KeyEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['get_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetKeyEvent', + request_serializer=analytics_admin.GetKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['get_key_event'] + + @property + def delete_key_event(self) -> Callable[ + [analytics_admin.DeleteKeyEventRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete key event method over gRPC. + + Deletes a Key Event. + + Returns: + Callable[[~.DeleteKeyEventRequest], + 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_key_event' not in self._stubs: + self._stubs['delete_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteKeyEvent', + request_serializer=analytics_admin.DeleteKeyEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_key_event'] + + @property + def list_key_events(self) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + Awaitable[analytics_admin.ListKeyEventsResponse]]: + r"""Return a callable for the list key events method over gRPC. + + Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + Returns: + Callable[[~.ListKeyEventsRequest], + Awaitable[~.ListKeyEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_events' not in self._stubs: + self._stubs['list_key_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListKeyEvents', + request_serializer=analytics_admin.ListKeyEventsRequest.serialize, + response_deserializer=analytics_admin.ListKeyEventsResponse.deserialize, + ) + return self._stubs['list_key_events'] + + @property + def get_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.GetDisplayVideo360AdvertiserLinkRequest], + Awaitable[resources.DisplayVideo360AdvertiserLink]]: + r"""Return a callable for the get display video360 + advertiser link method over gRPC. + + Look up a single DisplayVideo360AdvertiserLink + + Returns: + Callable[[~.GetDisplayVideo360AdvertiserLinkRequest], + Awaitable[~.DisplayVideo360AdvertiserLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link' not in self._stubs: + self._stubs['get_display_video360_advertiser_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDisplayVideo360AdvertiserLink', + request_serializer=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLink.deserialize, + ) + return self._stubs['get_display_video360_advertiser_link'] + + @property + def list_display_video360_advertiser_links(self) -> Callable[ + [analytics_admin.ListDisplayVideo360AdvertiserLinksRequest], + Awaitable[analytics_admin.ListDisplayVideo360AdvertiserLinksResponse]]: + r"""Return a callable for the list display video360 + advertiser links method over gRPC. + + Lists all DisplayVideo360AdvertiserLinks on a + property. + + Returns: + Callable[[~.ListDisplayVideo360AdvertiserLinksRequest], + Awaitable[~.ListDisplayVideo360AdvertiserLinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_links' not in self._stubs: + self._stubs['list_display_video360_advertiser_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListDisplayVideo360AdvertiserLinks', + request_serializer=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest.serialize, + response_deserializer=analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.deserialize, + ) + return self._stubs['list_display_video360_advertiser_links'] + + @property + def create_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest], + Awaitable[resources.DisplayVideo360AdvertiserLink]]: + r"""Return a callable for the create display video360 + advertiser link method over gRPC. + + Creates a DisplayVideo360AdvertiserLink. + This can only be utilized by users who have proper + authorization both on the Google Analytics property and + on the Display & Video 360 advertiser. Users who do not + have access to the Display & Video 360 advertiser should + instead seek to create a DisplayVideo360LinkProposal. + + Returns: + Callable[[~.CreateDisplayVideo360AdvertiserLinkRequest], + Awaitable[~.DisplayVideo360AdvertiserLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link' not in self._stubs: + self._stubs['create_display_video360_advertiser_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateDisplayVideo360AdvertiserLink', + request_serializer=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLink.deserialize, + ) + return self._stubs['create_display_video360_advertiser_link'] + + @property + def delete_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete display video360 + advertiser link method over gRPC. + + Deletes a DisplayVideo360AdvertiserLink on a + property. + + Returns: + Callable[[~.DeleteDisplayVideo360AdvertiserLinkRequest], + 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_display_video360_advertiser_link' not in self._stubs: + self._stubs['delete_display_video360_advertiser_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteDisplayVideo360AdvertiserLink', + request_serializer=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_display_video360_advertiser_link'] + + @property + def update_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest], + Awaitable[resources.DisplayVideo360AdvertiserLink]]: + r"""Return a callable for the update display video360 + advertiser link method over gRPC. + + Updates a DisplayVideo360AdvertiserLink on a + property. + + Returns: + Callable[[~.UpdateDisplayVideo360AdvertiserLinkRequest], + Awaitable[~.DisplayVideo360AdvertiserLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link' not in self._stubs: + self._stubs['update_display_video360_advertiser_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateDisplayVideo360AdvertiserLink', + request_serializer=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLink.deserialize, + ) + return self._stubs['update_display_video360_advertiser_link'] + + @property + def get_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest], + Awaitable[resources.DisplayVideo360AdvertiserLinkProposal]]: + r"""Return a callable for the get display video360 + advertiser link proposal method over gRPC. + + Lookup for a single + DisplayVideo360AdvertiserLinkProposal. + + Returns: + Callable[[~.GetDisplayVideo360AdvertiserLinkProposalRequest], + Awaitable[~.DisplayVideo360AdvertiserLinkProposal]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['get_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLinkProposal.deserialize, + ) + return self._stubs['get_display_video360_advertiser_link_proposal'] + + @property + def list_display_video360_advertiser_link_proposals(self) -> Callable[ + [analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest], + Awaitable[analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse]]: + r"""Return a callable for the list display video360 + advertiser link proposals method over gRPC. + + Lists DisplayVideo360AdvertiserLinkProposals on a + property. + + Returns: + Callable[[~.ListDisplayVideo360AdvertiserLinkProposalsRequest], + Awaitable[~.ListDisplayVideo360AdvertiserLinkProposalsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link_proposals' not in self._stubs: + self._stubs['list_display_video360_advertiser_link_proposals'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListDisplayVideo360AdvertiserLinkProposals', + request_serializer=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest.serialize, + response_deserializer=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.deserialize, + ) + return self._stubs['list_display_video360_advertiser_link_proposals'] + + @property + def create_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest], + Awaitable[resources.DisplayVideo360AdvertiserLinkProposal]]: + r"""Return a callable for the create display video360 + advertiser link proposal method over gRPC. + + Creates a DisplayVideo360AdvertiserLinkProposal. + + Returns: + Callable[[~.CreateDisplayVideo360AdvertiserLinkProposalRequest], + Awaitable[~.DisplayVideo360AdvertiserLinkProposal]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['create_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLinkProposal.deserialize, + ) + return self._stubs['create_display_video360_advertiser_link_proposal'] + + @property + def delete_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete display video360 + advertiser link proposal method over gRPC. + + Deletes a DisplayVideo360AdvertiserLinkProposal on a + property. This can only be used on cancelled proposals. + + Returns: + Callable[[~.DeleteDisplayVideo360AdvertiserLinkProposalRequest], + 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_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['delete_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_display_video360_advertiser_link_proposal'] + + @property + def approve_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest], + Awaitable[analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse]]: + r"""Return a callable for the approve display video360 + advertiser link proposal method over gRPC. + + Approves a DisplayVideo360AdvertiserLinkProposal. + The DisplayVideo360AdvertiserLinkProposal will be + deleted and a new DisplayVideo360AdvertiserLink will be + created. + + Returns: + Callable[[~.ApproveDisplayVideo360AdvertiserLinkProposalRequest], + Awaitable[~.ApproveDisplayVideo360AdvertiserLinkProposalResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'approve_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['approve_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ApproveDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.deserialize, + ) + return self._stubs['approve_display_video360_advertiser_link_proposal'] + + @property + def cancel_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest], + Awaitable[resources.DisplayVideo360AdvertiserLinkProposal]]: + r"""Return a callable for the cancel display video360 + advertiser link proposal method over gRPC. + + Cancels a DisplayVideo360AdvertiserLinkProposal. + Cancelling can mean either: + + - Declining a proposal initiated from Display & Video + 360 + - Withdrawing a proposal initiated from Google Analytics + After being cancelled, a proposal will eventually be + deleted automatically. + + Returns: + Callable[[~.CancelDisplayVideo360AdvertiserLinkProposalRequest], + Awaitable[~.DisplayVideo360AdvertiserLinkProposal]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'cancel_display_video360_advertiser_link_proposal' not in self._stubs: + self._stubs['cancel_display_video360_advertiser_link_proposal'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CancelDisplayVideo360AdvertiserLinkProposal', + request_serializer=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest.serialize, + response_deserializer=resources.DisplayVideo360AdvertiserLinkProposal.deserialize, + ) + return self._stubs['cancel_display_video360_advertiser_link_proposal'] + + @property + def create_custom_dimension(self) -> Callable[ + [analytics_admin.CreateCustomDimensionRequest], + Awaitable[resources.CustomDimension]]: + r"""Return a callable for the create custom dimension method over gRPC. + + Creates a CustomDimension. + + Returns: + Callable[[~.CreateCustomDimensionRequest], + Awaitable[~.CustomDimension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['create_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateCustomDimension', + request_serializer=analytics_admin.CreateCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['create_custom_dimension'] + + @property + def update_custom_dimension(self) -> Callable[ + [analytics_admin.UpdateCustomDimensionRequest], + Awaitable[resources.CustomDimension]]: + r"""Return a callable for the update custom dimension method over gRPC. + + Updates a CustomDimension on a property. + + Returns: + Callable[[~.UpdateCustomDimensionRequest], + Awaitable[~.CustomDimension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['update_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateCustomDimension', + request_serializer=analytics_admin.UpdateCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['update_custom_dimension'] + + @property + def list_custom_dimensions(self) -> Callable[ + [analytics_admin.ListCustomDimensionsRequest], + Awaitable[analytics_admin.ListCustomDimensionsResponse]]: + r"""Return a callable for the list custom dimensions method over gRPC. + + Lists CustomDimensions on a property. + + Returns: + Callable[[~.ListCustomDimensionsRequest], + Awaitable[~.ListCustomDimensionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimensions' not in self._stubs: + self._stubs['list_custom_dimensions'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListCustomDimensions', + request_serializer=analytics_admin.ListCustomDimensionsRequest.serialize, + response_deserializer=analytics_admin.ListCustomDimensionsResponse.deserialize, + ) + return self._stubs['list_custom_dimensions'] + + @property + def archive_custom_dimension(self) -> Callable[ + [analytics_admin.ArchiveCustomDimensionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the archive custom dimension method over gRPC. + + Archives a CustomDimension on a property. + + Returns: + Callable[[~.ArchiveCustomDimensionRequest], + 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 'archive_custom_dimension' not in self._stubs: + self._stubs['archive_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ArchiveCustomDimension', + request_serializer=analytics_admin.ArchiveCustomDimensionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_custom_dimension'] + + @property + def get_custom_dimension(self) -> Callable[ + [analytics_admin.GetCustomDimensionRequest], + Awaitable[resources.CustomDimension]]: + r"""Return a callable for the get custom dimension method over gRPC. + + Lookup for a single CustomDimension. + + Returns: + Callable[[~.GetCustomDimensionRequest], + Awaitable[~.CustomDimension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['get_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetCustomDimension', + request_serializer=analytics_admin.GetCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['get_custom_dimension'] + + @property + def create_custom_metric(self) -> Callable[ + [analytics_admin.CreateCustomMetricRequest], + Awaitable[resources.CustomMetric]]: + r"""Return a callable for the create custom metric method over gRPC. + + Creates a CustomMetric. + + Returns: + Callable[[~.CreateCustomMetricRequest], + Awaitable[~.CustomMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['create_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateCustomMetric', + request_serializer=analytics_admin.CreateCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['create_custom_metric'] + + @property + def update_custom_metric(self) -> Callable[ + [analytics_admin.UpdateCustomMetricRequest], + Awaitable[resources.CustomMetric]]: + r"""Return a callable for the update custom metric method over gRPC. + + Updates a CustomMetric on a property. + + Returns: + Callable[[~.UpdateCustomMetricRequest], + Awaitable[~.CustomMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['update_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateCustomMetric', + request_serializer=analytics_admin.UpdateCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['update_custom_metric'] + + @property + def list_custom_metrics(self) -> Callable[ + [analytics_admin.ListCustomMetricsRequest], + Awaitable[analytics_admin.ListCustomMetricsResponse]]: + r"""Return a callable for the list custom metrics method over gRPC. + + Lists CustomMetrics on a property. + + Returns: + Callable[[~.ListCustomMetricsRequest], + Awaitable[~.ListCustomMetricsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metrics' not in self._stubs: + self._stubs['list_custom_metrics'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListCustomMetrics', + request_serializer=analytics_admin.ListCustomMetricsRequest.serialize, + response_deserializer=analytics_admin.ListCustomMetricsResponse.deserialize, + ) + return self._stubs['list_custom_metrics'] + + @property + def archive_custom_metric(self) -> Callable[ + [analytics_admin.ArchiveCustomMetricRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the archive custom metric method over gRPC. + + Archives a CustomMetric on a property. + + Returns: + Callable[[~.ArchiveCustomMetricRequest], + 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 'archive_custom_metric' not in self._stubs: + self._stubs['archive_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ArchiveCustomMetric', + request_serializer=analytics_admin.ArchiveCustomMetricRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_custom_metric'] + + @property + def get_custom_metric(self) -> Callable[ + [analytics_admin.GetCustomMetricRequest], + Awaitable[resources.CustomMetric]]: + r"""Return a callable for the get custom metric method over gRPC. + + Lookup for a single CustomMetric. + + Returns: + Callable[[~.GetCustomMetricRequest], + Awaitable[~.CustomMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['get_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetCustomMetric', + request_serializer=analytics_admin.GetCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['get_custom_metric'] + + @property + def get_data_retention_settings(self) -> Callable[ + [analytics_admin.GetDataRetentionSettingsRequest], + Awaitable[resources.DataRetentionSettings]]: + r"""Return a callable for the get data retention settings method over gRPC. + + Returns the singleton data retention settings for + this property. + + Returns: + Callable[[~.GetDataRetentionSettingsRequest], + Awaitable[~.DataRetentionSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_retention_settings' not in self._stubs: + self._stubs['get_data_retention_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDataRetentionSettings', + request_serializer=analytics_admin.GetDataRetentionSettingsRequest.serialize, + response_deserializer=resources.DataRetentionSettings.deserialize, + ) + return self._stubs['get_data_retention_settings'] + + @property + def update_data_retention_settings(self) -> Callable[ + [analytics_admin.UpdateDataRetentionSettingsRequest], + Awaitable[resources.DataRetentionSettings]]: + r"""Return a callable for the update data retention settings method over gRPC. + + Updates the singleton data retention settings for + this property. + + Returns: + Callable[[~.UpdateDataRetentionSettingsRequest], + Awaitable[~.DataRetentionSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_retention_settings' not in self._stubs: + self._stubs['update_data_retention_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateDataRetentionSettings', + request_serializer=analytics_admin.UpdateDataRetentionSettingsRequest.serialize, + response_deserializer=resources.DataRetentionSettings.deserialize, + ) + return self._stubs['update_data_retention_settings'] + + @property + def create_data_stream(self) -> Callable[ + [analytics_admin.CreateDataStreamRequest], + Awaitable[resources.DataStream]]: + r"""Return a callable for the create data stream method over gRPC. + + Creates a DataStream. + + Returns: + Callable[[~.CreateDataStreamRequest], + Awaitable[~.DataStream]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_data_stream' not in self._stubs: + self._stubs['create_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateDataStream', + request_serializer=analytics_admin.CreateDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['create_data_stream'] + + @property + def delete_data_stream(self) -> Callable[ + [analytics_admin.DeleteDataStreamRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete data stream method over gRPC. + + Deletes a DataStream on a property. + + Returns: + Callable[[~.DeleteDataStreamRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_data_stream' not in self._stubs: + self._stubs['delete_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteDataStream', + request_serializer=analytics_admin.DeleteDataStreamRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_stream'] + + @property + def update_data_stream(self) -> Callable[ + [analytics_admin.UpdateDataStreamRequest], + Awaitable[resources.DataStream]]: + r"""Return a callable for the update data stream method over gRPC. + + Updates a DataStream on a property. + + Returns: + Callable[[~.UpdateDataStreamRequest], + Awaitable[~.DataStream]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_stream' not in self._stubs: + self._stubs['update_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateDataStream', + request_serializer=analytics_admin.UpdateDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['update_data_stream'] + + @property + def list_data_streams(self) -> Callable[ + [analytics_admin.ListDataStreamsRequest], + Awaitable[analytics_admin.ListDataStreamsResponse]]: + r"""Return a callable for the list data streams method over gRPC. + + Lists DataStreams on a property. + + Returns: + Callable[[~.ListDataStreamsRequest], + Awaitable[~.ListDataStreamsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_data_streams' not in self._stubs: + self._stubs['list_data_streams'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListDataStreams', + request_serializer=analytics_admin.ListDataStreamsRequest.serialize, + response_deserializer=analytics_admin.ListDataStreamsResponse.deserialize, + ) + return self._stubs['list_data_streams'] + + @property + def get_data_stream(self) -> Callable[ + [analytics_admin.GetDataStreamRequest], + Awaitable[resources.DataStream]]: + r"""Return a callable for the get data stream method over gRPC. + + Lookup for a single DataStream. + + Returns: + Callable[[~.GetDataStreamRequest], + Awaitable[~.DataStream]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_stream' not in self._stubs: + self._stubs['get_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDataStream', + request_serializer=analytics_admin.GetDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['get_data_stream'] + + @property + def get_audience(self) -> Callable[ + [analytics_admin.GetAudienceRequest], + Awaitable[audience.Audience]]: + r"""Return a callable for the get audience method over gRPC. + + Lookup for a single Audience. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. + + Returns: + Callable[[~.GetAudienceRequest], + Awaitable[~.Audience]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_audience' not in self._stubs: + self._stubs['get_audience'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAudience', + request_serializer=analytics_admin.GetAudienceRequest.serialize, + response_deserializer=audience.Audience.deserialize, + ) + return self._stubs['get_audience'] + + @property + def list_audiences(self) -> Callable[ + [analytics_admin.ListAudiencesRequest], + Awaitable[analytics_admin.ListAudiencesResponse]]: + r"""Return a callable for the list audiences method over gRPC. + + Lists Audiences on a property. + Audiences created before 2020 may not be supported. + Default audiences will not show filter definitions. + + Returns: + Callable[[~.ListAudiencesRequest], + Awaitable[~.ListAudiencesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_audiences' not in self._stubs: + self._stubs['list_audiences'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAudiences', + request_serializer=analytics_admin.ListAudiencesRequest.serialize, + response_deserializer=analytics_admin.ListAudiencesResponse.deserialize, + ) + return self._stubs['list_audiences'] + + @property + def create_audience(self) -> Callable[ + [analytics_admin.CreateAudienceRequest], + Awaitable[gaa_audience.Audience]]: + r"""Return a callable for the create audience method over gRPC. + + Creates an Audience. + + Returns: + Callable[[~.CreateAudienceRequest], + Awaitable[~.Audience]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_audience' not in self._stubs: + self._stubs['create_audience'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateAudience', + request_serializer=analytics_admin.CreateAudienceRequest.serialize, + response_deserializer=gaa_audience.Audience.deserialize, + ) + return self._stubs['create_audience'] + + @property + def update_audience(self) -> Callable[ + [analytics_admin.UpdateAudienceRequest], + Awaitable[gaa_audience.Audience]]: + r"""Return a callable for the update audience method over gRPC. + + Updates an Audience on a property. + + Returns: + Callable[[~.UpdateAudienceRequest], + Awaitable[~.Audience]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_audience' not in self._stubs: + self._stubs['update_audience'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateAudience', + request_serializer=analytics_admin.UpdateAudienceRequest.serialize, + response_deserializer=gaa_audience.Audience.deserialize, + ) + return self._stubs['update_audience'] + + @property + def archive_audience(self) -> Callable[ + [analytics_admin.ArchiveAudienceRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the archive audience method over gRPC. + + Archives an Audience on a property. + + Returns: + Callable[[~.ArchiveAudienceRequest], + 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 'archive_audience' not in self._stubs: + self._stubs['archive_audience'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ArchiveAudience', + request_serializer=analytics_admin.ArchiveAudienceRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_audience'] + + @property + def get_search_ads360_link(self) -> Callable[ + [analytics_admin.GetSearchAds360LinkRequest], + Awaitable[resources.SearchAds360Link]]: + r"""Return a callable for the get search ads360 link method over gRPC. + + Look up a single SearchAds360Link + + Returns: + Callable[[~.GetSearchAds360LinkRequest], + Awaitable[~.SearchAds360Link]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_search_ads360_link' not in self._stubs: + self._stubs['get_search_ads360_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetSearchAds360Link', + request_serializer=analytics_admin.GetSearchAds360LinkRequest.serialize, + response_deserializer=resources.SearchAds360Link.deserialize, + ) + return self._stubs['get_search_ads360_link'] + + @property + def list_search_ads360_links(self) -> Callable[ + [analytics_admin.ListSearchAds360LinksRequest], + Awaitable[analytics_admin.ListSearchAds360LinksResponse]]: + r"""Return a callable for the list search ads360 links method over gRPC. + + Lists all SearchAds360Links on a property. + + Returns: + Callable[[~.ListSearchAds360LinksRequest], + Awaitable[~.ListSearchAds360LinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_search_ads360_links' not in self._stubs: + self._stubs['list_search_ads360_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListSearchAds360Links', + request_serializer=analytics_admin.ListSearchAds360LinksRequest.serialize, + response_deserializer=analytics_admin.ListSearchAds360LinksResponse.deserialize, + ) + return self._stubs['list_search_ads360_links'] + + @property + def create_search_ads360_link(self) -> Callable[ + [analytics_admin.CreateSearchAds360LinkRequest], + Awaitable[resources.SearchAds360Link]]: + r"""Return a callable for the create search ads360 link method over gRPC. + + Creates a SearchAds360Link. + + Returns: + Callable[[~.CreateSearchAds360LinkRequest], + Awaitable[~.SearchAds360Link]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_search_ads360_link' not in self._stubs: + self._stubs['create_search_ads360_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateSearchAds360Link', + request_serializer=analytics_admin.CreateSearchAds360LinkRequest.serialize, + response_deserializer=resources.SearchAds360Link.deserialize, + ) + return self._stubs['create_search_ads360_link'] + + @property + def delete_search_ads360_link(self) -> Callable[ + [analytics_admin.DeleteSearchAds360LinkRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete search ads360 link method over gRPC. + + Deletes a SearchAds360Link on a property. + + Returns: + Callable[[~.DeleteSearchAds360LinkRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_search_ads360_link' not in self._stubs: + self._stubs['delete_search_ads360_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteSearchAds360Link', + request_serializer=analytics_admin.DeleteSearchAds360LinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_search_ads360_link'] + + @property + def update_search_ads360_link(self) -> Callable[ + [analytics_admin.UpdateSearchAds360LinkRequest], + Awaitable[resources.SearchAds360Link]]: + r"""Return a callable for the update search ads360 link method over gRPC. + + Updates a SearchAds360Link on a property. + + Returns: + Callable[[~.UpdateSearchAds360LinkRequest], + Awaitable[~.SearchAds360Link]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_search_ads360_link' not in self._stubs: + self._stubs['update_search_ads360_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateSearchAds360Link', + request_serializer=analytics_admin.UpdateSearchAds360LinkRequest.serialize, + response_deserializer=resources.SearchAds360Link.deserialize, + ) + return self._stubs['update_search_ads360_link'] + + @property + def get_attribution_settings(self) -> Callable[ + [analytics_admin.GetAttributionSettingsRequest], + Awaitable[resources.AttributionSettings]]: + r"""Return a callable for the get attribution settings method over gRPC. + + Lookup for a AttributionSettings singleton. + + Returns: + Callable[[~.GetAttributionSettingsRequest], + Awaitable[~.AttributionSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attribution_settings' not in self._stubs: + self._stubs['get_attribution_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAttributionSettings', + request_serializer=analytics_admin.GetAttributionSettingsRequest.serialize, + response_deserializer=resources.AttributionSettings.deserialize, + ) + return self._stubs['get_attribution_settings'] + + @property + def update_attribution_settings(self) -> Callable[ + [analytics_admin.UpdateAttributionSettingsRequest], + Awaitable[resources.AttributionSettings]]: + r"""Return a callable for the update attribution settings method over gRPC. + + Updates attribution settings on a property. + + Returns: + Callable[[~.UpdateAttributionSettingsRequest], + Awaitable[~.AttributionSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_attribution_settings' not in self._stubs: + self._stubs['update_attribution_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateAttributionSettings', + request_serializer=analytics_admin.UpdateAttributionSettingsRequest.serialize, + response_deserializer=resources.AttributionSettings.deserialize, + ) + return self._stubs['update_attribution_settings'] + + @property + def run_access_report(self) -> Callable[ + [analytics_admin.RunAccessReportRequest], + Awaitable[analytics_admin.RunAccessReportResponse]]: + r"""Return a callable for the run access report method over gRPC. + + Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. + + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. + + Returns: + Callable[[~.RunAccessReportRequest], + Awaitable[~.RunAccessReportResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_access_report' not in self._stubs: + self._stubs['run_access_report'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/RunAccessReport', + request_serializer=analytics_admin.RunAccessReportRequest.serialize, + response_deserializer=analytics_admin.RunAccessReportResponse.deserialize, + ) + return self._stubs['run_access_report'] + + @property + def create_access_binding(self) -> Callable[ + [analytics_admin.CreateAccessBindingRequest], + Awaitable[resources.AccessBinding]]: + r"""Return a callable for the create access binding method over gRPC. + + Creates an access binding on an account or property. + + Returns: + Callable[[~.CreateAccessBindingRequest], + Awaitable[~.AccessBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_access_binding' not in self._stubs: + self._stubs['create_access_binding'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateAccessBinding', + request_serializer=analytics_admin.CreateAccessBindingRequest.serialize, + response_deserializer=resources.AccessBinding.deserialize, + ) + return self._stubs['create_access_binding'] + + @property + def get_access_binding(self) -> Callable[ + [analytics_admin.GetAccessBindingRequest], + Awaitable[resources.AccessBinding]]: + r"""Return a callable for the get access binding method over gRPC. + + Gets information about an access binding. + + Returns: + Callable[[~.GetAccessBindingRequest], + Awaitable[~.AccessBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_access_binding' not in self._stubs: + self._stubs['get_access_binding'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAccessBinding', + request_serializer=analytics_admin.GetAccessBindingRequest.serialize, + response_deserializer=resources.AccessBinding.deserialize, + ) + return self._stubs['get_access_binding'] + + @property + def update_access_binding(self) -> Callable[ + [analytics_admin.UpdateAccessBindingRequest], + Awaitable[resources.AccessBinding]]: + r"""Return a callable for the update access binding method over gRPC. + + Updates an access binding on an account or property. + + Returns: + Callable[[~.UpdateAccessBindingRequest], + Awaitable[~.AccessBinding]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_access_binding' not in self._stubs: + self._stubs['update_access_binding'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateAccessBinding', + request_serializer=analytics_admin.UpdateAccessBindingRequest.serialize, + response_deserializer=resources.AccessBinding.deserialize, + ) + return self._stubs['update_access_binding'] + + @property + def delete_access_binding(self) -> Callable[ + [analytics_admin.DeleteAccessBindingRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete access binding method over gRPC. + + Deletes an access binding on an account or property. + + Returns: + Callable[[~.DeleteAccessBindingRequest], + 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_access_binding' not in self._stubs: + self._stubs['delete_access_binding'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteAccessBinding', + request_serializer=analytics_admin.DeleteAccessBindingRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_access_binding'] + + @property + def list_access_bindings(self) -> Callable[ + [analytics_admin.ListAccessBindingsRequest], + Awaitable[analytics_admin.ListAccessBindingsResponse]]: + r"""Return a callable for the list access bindings method over gRPC. + + Lists all access bindings on an account or property. + + Returns: + Callable[[~.ListAccessBindingsRequest], + Awaitable[~.ListAccessBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_access_bindings' not in self._stubs: + self._stubs['list_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAccessBindings', + request_serializer=analytics_admin.ListAccessBindingsRequest.serialize, + response_deserializer=analytics_admin.ListAccessBindingsResponse.deserialize, + ) + return self._stubs['list_access_bindings'] + + @property + def batch_create_access_bindings(self) -> Callable[ + [analytics_admin.BatchCreateAccessBindingsRequest], + Awaitable[analytics_admin.BatchCreateAccessBindingsResponse]]: + r"""Return a callable for the batch create access bindings method over gRPC. + + Creates information about multiple access bindings to + an account or property. + + This method is transactional. If any AccessBinding + cannot be created, none of the AccessBindings will be + created. + + Returns: + Callable[[~.BatchCreateAccessBindingsRequest], + Awaitable[~.BatchCreateAccessBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_create_access_bindings' not in self._stubs: + self._stubs['batch_create_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/BatchCreateAccessBindings', + request_serializer=analytics_admin.BatchCreateAccessBindingsRequest.serialize, + response_deserializer=analytics_admin.BatchCreateAccessBindingsResponse.deserialize, + ) + return self._stubs['batch_create_access_bindings'] + + @property + def batch_get_access_bindings(self) -> Callable[ + [analytics_admin.BatchGetAccessBindingsRequest], + Awaitable[analytics_admin.BatchGetAccessBindingsResponse]]: + r"""Return a callable for the batch get access bindings method over gRPC. + + Gets information about multiple access bindings to an + account or property. + + Returns: + Callable[[~.BatchGetAccessBindingsRequest], + Awaitable[~.BatchGetAccessBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_get_access_bindings' not in self._stubs: + self._stubs['batch_get_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/BatchGetAccessBindings', + request_serializer=analytics_admin.BatchGetAccessBindingsRequest.serialize, + response_deserializer=analytics_admin.BatchGetAccessBindingsResponse.deserialize, + ) + return self._stubs['batch_get_access_bindings'] + + @property + def batch_update_access_bindings(self) -> Callable[ + [analytics_admin.BatchUpdateAccessBindingsRequest], + Awaitable[analytics_admin.BatchUpdateAccessBindingsResponse]]: + r"""Return a callable for the batch update access bindings method over gRPC. + + Updates information about multiple access bindings to + an account or property. + + Returns: + Callable[[~.BatchUpdateAccessBindingsRequest], + Awaitable[~.BatchUpdateAccessBindingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'batch_update_access_bindings' not in self._stubs: + self._stubs['batch_update_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/BatchUpdateAccessBindings', + request_serializer=analytics_admin.BatchUpdateAccessBindingsRequest.serialize, + response_deserializer=analytics_admin.BatchUpdateAccessBindingsResponse.deserialize, + ) + return self._stubs['batch_update_access_bindings'] + + @property + def batch_delete_access_bindings(self) -> Callable[ + [analytics_admin.BatchDeleteAccessBindingsRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the batch delete access bindings method over gRPC. + + Deletes information about multiple users' links to an + account or property. + + Returns: + Callable[[~.BatchDeleteAccessBindingsRequest], + 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 'batch_delete_access_bindings' not in self._stubs: + self._stubs['batch_delete_access_bindings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/BatchDeleteAccessBindings', + request_serializer=analytics_admin.BatchDeleteAccessBindingsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['batch_delete_access_bindings'] + + @property + def get_expanded_data_set(self) -> Callable[ + [analytics_admin.GetExpandedDataSetRequest], + Awaitable[expanded_data_set.ExpandedDataSet]]: + r"""Return a callable for the get expanded data set method over gRPC. + + Lookup for a single ExpandedDataSet. + + Returns: + Callable[[~.GetExpandedDataSetRequest], + Awaitable[~.ExpandedDataSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_expanded_data_set' not in self._stubs: + self._stubs['get_expanded_data_set'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetExpandedDataSet', + request_serializer=analytics_admin.GetExpandedDataSetRequest.serialize, + response_deserializer=expanded_data_set.ExpandedDataSet.deserialize, + ) + return self._stubs['get_expanded_data_set'] + + @property + def list_expanded_data_sets(self) -> Callable[ + [analytics_admin.ListExpandedDataSetsRequest], + Awaitable[analytics_admin.ListExpandedDataSetsResponse]]: + r"""Return a callable for the list expanded data sets method over gRPC. + + Lists ExpandedDataSets on a property. + + Returns: + Callable[[~.ListExpandedDataSetsRequest], + Awaitable[~.ListExpandedDataSetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_expanded_data_sets' not in self._stubs: + self._stubs['list_expanded_data_sets'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListExpandedDataSets', + request_serializer=analytics_admin.ListExpandedDataSetsRequest.serialize, + response_deserializer=analytics_admin.ListExpandedDataSetsResponse.deserialize, + ) + return self._stubs['list_expanded_data_sets'] + + @property + def create_expanded_data_set(self) -> Callable[ + [analytics_admin.CreateExpandedDataSetRequest], + Awaitable[gaa_expanded_data_set.ExpandedDataSet]]: + r"""Return a callable for the create expanded data set method over gRPC. + + Creates a ExpandedDataSet. + + Returns: + Callable[[~.CreateExpandedDataSetRequest], + Awaitable[~.ExpandedDataSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_expanded_data_set' not in self._stubs: + self._stubs['create_expanded_data_set'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateExpandedDataSet', + request_serializer=analytics_admin.CreateExpandedDataSetRequest.serialize, + response_deserializer=gaa_expanded_data_set.ExpandedDataSet.deserialize, + ) + return self._stubs['create_expanded_data_set'] + + @property + def update_expanded_data_set(self) -> Callable[ + [analytics_admin.UpdateExpandedDataSetRequest], + Awaitable[gaa_expanded_data_set.ExpandedDataSet]]: + r"""Return a callable for the update expanded data set method over gRPC. + + Updates a ExpandedDataSet on a property. + + Returns: + Callable[[~.UpdateExpandedDataSetRequest], + Awaitable[~.ExpandedDataSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_expanded_data_set' not in self._stubs: + self._stubs['update_expanded_data_set'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateExpandedDataSet', + request_serializer=analytics_admin.UpdateExpandedDataSetRequest.serialize, + response_deserializer=gaa_expanded_data_set.ExpandedDataSet.deserialize, + ) + return self._stubs['update_expanded_data_set'] + + @property + def delete_expanded_data_set(self) -> Callable[ + [analytics_admin.DeleteExpandedDataSetRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete expanded data set method over gRPC. + + Deletes a ExpandedDataSet on a property. + + Returns: + Callable[[~.DeleteExpandedDataSetRequest], + 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_expanded_data_set' not in self._stubs: + self._stubs['delete_expanded_data_set'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteExpandedDataSet', + request_serializer=analytics_admin.DeleteExpandedDataSetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_expanded_data_set'] + + @property + def get_channel_group(self) -> Callable[ + [analytics_admin.GetChannelGroupRequest], + Awaitable[channel_group.ChannelGroup]]: + r"""Return a callable for the get channel group method over gRPC. + + Lookup for a single ChannelGroup. + + Returns: + Callable[[~.GetChannelGroupRequest], + Awaitable[~.ChannelGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel_group' not in self._stubs: + self._stubs['get_channel_group'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetChannelGroup', + request_serializer=analytics_admin.GetChannelGroupRequest.serialize, + response_deserializer=channel_group.ChannelGroup.deserialize, + ) + return self._stubs['get_channel_group'] + + @property + def list_channel_groups(self) -> Callable[ + [analytics_admin.ListChannelGroupsRequest], + Awaitable[analytics_admin.ListChannelGroupsResponse]]: + r"""Return a callable for the list channel groups method over gRPC. + + Lists ChannelGroups on a property. + + Returns: + Callable[[~.ListChannelGroupsRequest], + Awaitable[~.ListChannelGroupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel_groups' not in self._stubs: + self._stubs['list_channel_groups'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListChannelGroups', + request_serializer=analytics_admin.ListChannelGroupsRequest.serialize, + response_deserializer=analytics_admin.ListChannelGroupsResponse.deserialize, + ) + return self._stubs['list_channel_groups'] + + @property + def create_channel_group(self) -> Callable[ + [analytics_admin.CreateChannelGroupRequest], + Awaitable[gaa_channel_group.ChannelGroup]]: + r"""Return a callable for the create channel group method over gRPC. + + Creates a ChannelGroup. + + Returns: + Callable[[~.CreateChannelGroupRequest], + Awaitable[~.ChannelGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel_group' not in self._stubs: + self._stubs['create_channel_group'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateChannelGroup', + request_serializer=analytics_admin.CreateChannelGroupRequest.serialize, + response_deserializer=gaa_channel_group.ChannelGroup.deserialize, + ) + return self._stubs['create_channel_group'] + + @property + def update_channel_group(self) -> Callable[ + [analytics_admin.UpdateChannelGroupRequest], + Awaitable[gaa_channel_group.ChannelGroup]]: + r"""Return a callable for the update channel group method over gRPC. + + Updates a ChannelGroup. + + Returns: + Callable[[~.UpdateChannelGroupRequest], + Awaitable[~.ChannelGroup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_channel_group' not in self._stubs: + self._stubs['update_channel_group'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateChannelGroup', + request_serializer=analytics_admin.UpdateChannelGroupRequest.serialize, + response_deserializer=gaa_channel_group.ChannelGroup.deserialize, + ) + return self._stubs['update_channel_group'] + + @property + def delete_channel_group(self) -> Callable[ + [analytics_admin.DeleteChannelGroupRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete channel group method over gRPC. + + Deletes a ChannelGroup on a property. + + Returns: + Callable[[~.DeleteChannelGroupRequest], + 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_channel_group' not in self._stubs: + self._stubs['delete_channel_group'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteChannelGroup', + request_serializer=analytics_admin.DeleteChannelGroupRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_channel_group'] + + @property + def set_automated_ga4_configuration_opt_out(self) -> Callable[ + [analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest], + Awaitable[analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse]]: + r"""Return a callable for the set automated ga4 + configuration opt out method over gRPC. + + Sets the opt out status for the automated GA4 setup + process for a UA property. + Note: this has no effect on GA4 property. + + Returns: + Callable[[~.SetAutomatedGa4ConfigurationOptOutRequest], + Awaitable[~.SetAutomatedGa4ConfigurationOptOutResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_automated_ga4_configuration_opt_out' not in self._stubs: + self._stubs['set_automated_ga4_configuration_opt_out'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/SetAutomatedGa4ConfigurationOptOut', + request_serializer=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest.serialize, + response_deserializer=analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.deserialize, + ) + return self._stubs['set_automated_ga4_configuration_opt_out'] + + @property + def fetch_automated_ga4_configuration_opt_out(self) -> Callable[ + [analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest], + Awaitable[analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse]]: + r"""Return a callable for the fetch automated ga4 + configuration opt out method over gRPC. + + Fetches the opt out status for the automated GA4 + setup process for a UA property. + Note: this has no effect on GA4 property. + + Returns: + Callable[[~.FetchAutomatedGa4ConfigurationOptOutRequest], + Awaitable[~.FetchAutomatedGa4ConfigurationOptOutResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_automated_ga4_configuration_opt_out' not in self._stubs: + self._stubs['fetch_automated_ga4_configuration_opt_out'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/FetchAutomatedGa4ConfigurationOptOut', + request_serializer=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest.serialize, + response_deserializer=analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.deserialize, + ) + return self._stubs['fetch_automated_ga4_configuration_opt_out'] + + @property + def create_big_query_link(self) -> Callable[ + [analytics_admin.CreateBigQueryLinkRequest], + Awaitable[resources.BigQueryLink]]: + r"""Return a callable for the create big query link method over gRPC. + + Creates a BigQueryLink. + + Returns: + Callable[[~.CreateBigQueryLinkRequest], + Awaitable[~.BigQueryLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_link' not in self._stubs: + self._stubs['create_big_query_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateBigQueryLink', + request_serializer=analytics_admin.CreateBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs['create_big_query_link'] + + @property + def get_big_query_link(self) -> Callable[ + [analytics_admin.GetBigQueryLinkRequest], + Awaitable[resources.BigQueryLink]]: + r"""Return a callable for the get big query link method over gRPC. + + Lookup for a single BigQuery Link. + + Returns: + Callable[[~.GetBigQueryLinkRequest], + Awaitable[~.BigQueryLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_link' not in self._stubs: + self._stubs['get_big_query_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetBigQueryLink', + request_serializer=analytics_admin.GetBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs['get_big_query_link'] + + @property + def list_big_query_links(self) -> Callable[ + [analytics_admin.ListBigQueryLinksRequest], + Awaitable[analytics_admin.ListBigQueryLinksResponse]]: + r"""Return a callable for the list big query links method over gRPC. + + Lists BigQuery Links on a property. + + Returns: + Callable[[~.ListBigQueryLinksRequest], + Awaitable[~.ListBigQueryLinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_links' not in self._stubs: + self._stubs['list_big_query_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListBigQueryLinks', + request_serializer=analytics_admin.ListBigQueryLinksRequest.serialize, + response_deserializer=analytics_admin.ListBigQueryLinksResponse.deserialize, + ) + return self._stubs['list_big_query_links'] + + @property + def delete_big_query_link(self) -> Callable[ + [analytics_admin.DeleteBigQueryLinkRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete big query link method over gRPC. + + Deletes a BigQueryLink on a property. + + Returns: + Callable[[~.DeleteBigQueryLinkRequest], + 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_big_query_link' not in self._stubs: + self._stubs['delete_big_query_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteBigQueryLink', + request_serializer=analytics_admin.DeleteBigQueryLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_big_query_link'] + + @property + def update_big_query_link(self) -> Callable[ + [analytics_admin.UpdateBigQueryLinkRequest], + Awaitable[resources.BigQueryLink]]: + r"""Return a callable for the update big query link method over gRPC. + + Updates a BigQueryLink. + + Returns: + Callable[[~.UpdateBigQueryLinkRequest], + Awaitable[~.BigQueryLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_big_query_link' not in self._stubs: + self._stubs['update_big_query_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateBigQueryLink', + request_serializer=analytics_admin.UpdateBigQueryLinkRequest.serialize, + response_deserializer=resources.BigQueryLink.deserialize, + ) + return self._stubs['update_big_query_link'] + + @property + def get_enhanced_measurement_settings(self) -> Callable[ + [analytics_admin.GetEnhancedMeasurementSettingsRequest], + Awaitable[resources.EnhancedMeasurementSettings]]: + r"""Return a callable for the get enhanced measurement + settings method over gRPC. + + Returns the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Returns: + Callable[[~.GetEnhancedMeasurementSettingsRequest], + Awaitable[~.EnhancedMeasurementSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_enhanced_measurement_settings' not in self._stubs: + self._stubs['get_enhanced_measurement_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetEnhancedMeasurementSettings', + request_serializer=analytics_admin.GetEnhancedMeasurementSettingsRequest.serialize, + response_deserializer=resources.EnhancedMeasurementSettings.deserialize, + ) + return self._stubs['get_enhanced_measurement_settings'] + + @property + def update_enhanced_measurement_settings(self) -> Callable[ + [analytics_admin.UpdateEnhancedMeasurementSettingsRequest], + Awaitable[resources.EnhancedMeasurementSettings]]: + r"""Return a callable for the update enhanced measurement + settings method over gRPC. + + Updates the enhanced measurement settings for this + data stream. Note that the stream must enable enhanced + measurement for these settings to take effect. + + Returns: + Callable[[~.UpdateEnhancedMeasurementSettingsRequest], + Awaitable[~.EnhancedMeasurementSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_enhanced_measurement_settings' not in self._stubs: + self._stubs['update_enhanced_measurement_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateEnhancedMeasurementSettings', + request_serializer=analytics_admin.UpdateEnhancedMeasurementSettingsRequest.serialize, + response_deserializer=resources.EnhancedMeasurementSettings.deserialize, + ) + return self._stubs['update_enhanced_measurement_settings'] + + @property + def create_connected_site_tag(self) -> Callable[ + [analytics_admin.CreateConnectedSiteTagRequest], + Awaitable[analytics_admin.CreateConnectedSiteTagResponse]]: + r"""Return a callable for the create connected site tag method over gRPC. + + Creates a connected site tag for a Universal + Analytics property. You can create a maximum of 20 + connected site tags per property. Note: This API cannot + be used on GA4 properties. + + Returns: + Callable[[~.CreateConnectedSiteTagRequest], + Awaitable[~.CreateConnectedSiteTagResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connected_site_tag' not in self._stubs: + self._stubs['create_connected_site_tag'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateConnectedSiteTag', + request_serializer=analytics_admin.CreateConnectedSiteTagRequest.serialize, + response_deserializer=analytics_admin.CreateConnectedSiteTagResponse.deserialize, + ) + return self._stubs['create_connected_site_tag'] + + @property + def delete_connected_site_tag(self) -> Callable[ + [analytics_admin.DeleteConnectedSiteTagRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete connected site tag method over gRPC. + + Deletes a connected site tag for a Universal + Analytics property. Note: this has no effect on GA4 + properties. + + Returns: + Callable[[~.DeleteConnectedSiteTagRequest], + 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_connected_site_tag' not in self._stubs: + self._stubs['delete_connected_site_tag'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteConnectedSiteTag', + request_serializer=analytics_admin.DeleteConnectedSiteTagRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_connected_site_tag'] + + @property + def list_connected_site_tags(self) -> Callable[ + [analytics_admin.ListConnectedSiteTagsRequest], + Awaitable[analytics_admin.ListConnectedSiteTagsResponse]]: + r"""Return a callable for the list connected site tags method over gRPC. + + Lists the connected site tags for a Universal + Analytics property. A maximum of 20 connected site tags + will be returned. Note: this has no effect on GA4 + property. + + Returns: + Callable[[~.ListConnectedSiteTagsRequest], + Awaitable[~.ListConnectedSiteTagsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_connected_site_tags' not in self._stubs: + self._stubs['list_connected_site_tags'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListConnectedSiteTags', + request_serializer=analytics_admin.ListConnectedSiteTagsRequest.serialize, + response_deserializer=analytics_admin.ListConnectedSiteTagsResponse.deserialize, + ) + return self._stubs['list_connected_site_tags'] + + @property + def fetch_connected_ga4_property(self) -> Callable[ + [analytics_admin.FetchConnectedGa4PropertyRequest], + Awaitable[analytics_admin.FetchConnectedGa4PropertyResponse]]: + r"""Return a callable for the fetch connected ga4 property method over gRPC. + + Given a specified UA property, looks up the GA4 + property connected to it. Note: this cannot be used with + GA4 properties. + + Returns: + Callable[[~.FetchConnectedGa4PropertyRequest], + Awaitable[~.FetchConnectedGa4PropertyResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'fetch_connected_ga4_property' not in self._stubs: + self._stubs['fetch_connected_ga4_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/FetchConnectedGa4Property', + request_serializer=analytics_admin.FetchConnectedGa4PropertyRequest.serialize, + response_deserializer=analytics_admin.FetchConnectedGa4PropertyResponse.deserialize, + ) + return self._stubs['fetch_connected_ga4_property'] + + @property + def get_ad_sense_link(self) -> Callable[ + [analytics_admin.GetAdSenseLinkRequest], + Awaitable[resources.AdSenseLink]]: + r"""Return a callable for the get ad sense link method over gRPC. + + Looks up a single AdSenseLink. + + Returns: + Callable[[~.GetAdSenseLinkRequest], + Awaitable[~.AdSenseLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ad_sense_link' not in self._stubs: + self._stubs['get_ad_sense_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetAdSenseLink', + request_serializer=analytics_admin.GetAdSenseLinkRequest.serialize, + response_deserializer=resources.AdSenseLink.deserialize, + ) + return self._stubs['get_ad_sense_link'] + + @property + def create_ad_sense_link(self) -> Callable[ + [analytics_admin.CreateAdSenseLinkRequest], + Awaitable[resources.AdSenseLink]]: + r"""Return a callable for the create ad sense link method over gRPC. + + Creates an AdSenseLink. + + Returns: + Callable[[~.CreateAdSenseLinkRequest], + Awaitable[~.AdSenseLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ad_sense_link' not in self._stubs: + self._stubs['create_ad_sense_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateAdSenseLink', + request_serializer=analytics_admin.CreateAdSenseLinkRequest.serialize, + response_deserializer=resources.AdSenseLink.deserialize, + ) + return self._stubs['create_ad_sense_link'] + + @property + def delete_ad_sense_link(self) -> Callable[ + [analytics_admin.DeleteAdSenseLinkRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete ad sense link method over gRPC. + + Deletes an AdSenseLink. + + Returns: + Callable[[~.DeleteAdSenseLinkRequest], + 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_ad_sense_link' not in self._stubs: + self._stubs['delete_ad_sense_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteAdSenseLink', + request_serializer=analytics_admin.DeleteAdSenseLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_ad_sense_link'] + + @property + def list_ad_sense_links(self) -> Callable[ + [analytics_admin.ListAdSenseLinksRequest], + Awaitable[analytics_admin.ListAdSenseLinksResponse]]: + r"""Return a callable for the list ad sense links method over gRPC. + + Lists AdSenseLinks on a property. + + Returns: + Callable[[~.ListAdSenseLinksRequest], + Awaitable[~.ListAdSenseLinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ad_sense_links' not in self._stubs: + self._stubs['list_ad_sense_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListAdSenseLinks', + request_serializer=analytics_admin.ListAdSenseLinksRequest.serialize, + response_deserializer=analytics_admin.ListAdSenseLinksResponse.deserialize, + ) + return self._stubs['list_ad_sense_links'] + + @property + def get_event_create_rule(self) -> Callable[ + [analytics_admin.GetEventCreateRuleRequest], + Awaitable[event_create_and_edit.EventCreateRule]]: + r"""Return a callable for the get event create rule method over gRPC. + + Lookup for a single EventCreateRule. + + Returns: + Callable[[~.GetEventCreateRuleRequest], + Awaitable[~.EventCreateRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_event_create_rule' not in self._stubs: + self._stubs['get_event_create_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetEventCreateRule', + request_serializer=analytics_admin.GetEventCreateRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventCreateRule.deserialize, + ) + return self._stubs['get_event_create_rule'] + + @property + def list_event_create_rules(self) -> Callable[ + [analytics_admin.ListEventCreateRulesRequest], + Awaitable[analytics_admin.ListEventCreateRulesResponse]]: + r"""Return a callable for the list event create rules method over gRPC. + + Lists EventCreateRules on a web data stream. + + Returns: + Callable[[~.ListEventCreateRulesRequest], + Awaitable[~.ListEventCreateRulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_create_rules' not in self._stubs: + self._stubs['list_event_create_rules'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListEventCreateRules', + request_serializer=analytics_admin.ListEventCreateRulesRequest.serialize, + response_deserializer=analytics_admin.ListEventCreateRulesResponse.deserialize, + ) + return self._stubs['list_event_create_rules'] + + @property + def create_event_create_rule(self) -> Callable[ + [analytics_admin.CreateEventCreateRuleRequest], + Awaitable[event_create_and_edit.EventCreateRule]]: + r"""Return a callable for the create event create rule method over gRPC. + + Creates an EventCreateRule. + + Returns: + Callable[[~.CreateEventCreateRuleRequest], + Awaitable[~.EventCreateRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_event_create_rule' not in self._stubs: + self._stubs['create_event_create_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateEventCreateRule', + request_serializer=analytics_admin.CreateEventCreateRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventCreateRule.deserialize, + ) + return self._stubs['create_event_create_rule'] + + @property + def update_event_create_rule(self) -> Callable[ + [analytics_admin.UpdateEventCreateRuleRequest], + Awaitable[event_create_and_edit.EventCreateRule]]: + r"""Return a callable for the update event create rule method over gRPC. + + Updates an EventCreateRule. + + Returns: + Callable[[~.UpdateEventCreateRuleRequest], + Awaitable[~.EventCreateRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_event_create_rule' not in self._stubs: + self._stubs['update_event_create_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateEventCreateRule', + request_serializer=analytics_admin.UpdateEventCreateRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventCreateRule.deserialize, + ) + return self._stubs['update_event_create_rule'] + + @property + def delete_event_create_rule(self) -> Callable[ + [analytics_admin.DeleteEventCreateRuleRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete event create rule method over gRPC. + + Deletes an EventCreateRule. + + Returns: + Callable[[~.DeleteEventCreateRuleRequest], + 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_event_create_rule' not in self._stubs: + self._stubs['delete_event_create_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteEventCreateRule', + request_serializer=analytics_admin.DeleteEventCreateRuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_event_create_rule'] + + @property + def get_event_edit_rule(self) -> Callable[ + [analytics_admin.GetEventEditRuleRequest], + Awaitable[event_create_and_edit.EventEditRule]]: + r"""Return a callable for the get event edit rule method over gRPC. + + Lookup for a single EventEditRule. + + Returns: + Callable[[~.GetEventEditRuleRequest], + Awaitable[~.EventEditRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_event_edit_rule' not in self._stubs: + self._stubs['get_event_edit_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetEventEditRule', + request_serializer=analytics_admin.GetEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs['get_event_edit_rule'] + + @property + def list_event_edit_rules(self) -> Callable[ + [analytics_admin.ListEventEditRulesRequest], + Awaitable[analytics_admin.ListEventEditRulesResponse]]: + r"""Return a callable for the list event edit rules method over gRPC. + + Lists EventEditRules on a web data stream. + + Returns: + Callable[[~.ListEventEditRulesRequest], + Awaitable[~.ListEventEditRulesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_event_edit_rules' not in self._stubs: + self._stubs['list_event_edit_rules'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListEventEditRules', + request_serializer=analytics_admin.ListEventEditRulesRequest.serialize, + response_deserializer=analytics_admin.ListEventEditRulesResponse.deserialize, + ) + return self._stubs['list_event_edit_rules'] + + @property + def create_event_edit_rule(self) -> Callable[ + [analytics_admin.CreateEventEditRuleRequest], + Awaitable[event_create_and_edit.EventEditRule]]: + r"""Return a callable for the create event edit rule method over gRPC. + + Creates an EventEditRule. + + Returns: + Callable[[~.CreateEventEditRuleRequest], + Awaitable[~.EventEditRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_event_edit_rule' not in self._stubs: + self._stubs['create_event_edit_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateEventEditRule', + request_serializer=analytics_admin.CreateEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs['create_event_edit_rule'] + + @property + def update_event_edit_rule(self) -> Callable[ + [analytics_admin.UpdateEventEditRuleRequest], + Awaitable[event_create_and_edit.EventEditRule]]: + r"""Return a callable for the update event edit rule method over gRPC. + + Updates an EventEditRule. + + Returns: + Callable[[~.UpdateEventEditRuleRequest], + Awaitable[~.EventEditRule]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_event_edit_rule' not in self._stubs: + self._stubs['update_event_edit_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateEventEditRule', + request_serializer=analytics_admin.UpdateEventEditRuleRequest.serialize, + response_deserializer=event_create_and_edit.EventEditRule.deserialize, + ) + return self._stubs['update_event_edit_rule'] + + @property + def delete_event_edit_rule(self) -> Callable[ + [analytics_admin.DeleteEventEditRuleRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete event edit rule method over gRPC. + + Deletes an EventEditRule. + + Returns: + Callable[[~.DeleteEventEditRuleRequest], + 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_event_edit_rule' not in self._stubs: + self._stubs['delete_event_edit_rule'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteEventEditRule', + request_serializer=analytics_admin.DeleteEventEditRuleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_event_edit_rule'] + + @property + def reorder_event_edit_rules(self) -> Callable[ + [analytics_admin.ReorderEventEditRulesRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the reorder event edit rules method over gRPC. + + Changes the processing order of event edit rules on + the specified stream. + + Returns: + Callable[[~.ReorderEventEditRulesRequest], + 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 'reorder_event_edit_rules' not in self._stubs: + self._stubs['reorder_event_edit_rules'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ReorderEventEditRules', + request_serializer=analytics_admin.ReorderEventEditRulesRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['reorder_event_edit_rules'] + + @property + def update_data_redaction_settings(self) -> Callable[ + [analytics_admin.UpdateDataRedactionSettingsRequest], + Awaitable[resources.DataRedactionSettings]]: + r"""Return a callable for the update data redaction settings method over gRPC. + + Updates a DataRedactionSettings on a property. + + Returns: + Callable[[~.UpdateDataRedactionSettingsRequest], + Awaitable[~.DataRedactionSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_redaction_settings' not in self._stubs: + self._stubs['update_data_redaction_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateDataRedactionSettings', + request_serializer=analytics_admin.UpdateDataRedactionSettingsRequest.serialize, + response_deserializer=resources.DataRedactionSettings.deserialize, + ) + return self._stubs['update_data_redaction_settings'] + + @property + def get_data_redaction_settings(self) -> Callable[ + [analytics_admin.GetDataRedactionSettingsRequest], + Awaitable[resources.DataRedactionSettings]]: + r"""Return a callable for the get data redaction settings method over gRPC. + + Lookup for a single DataRedactionSettings. + + Returns: + Callable[[~.GetDataRedactionSettingsRequest], + Awaitable[~.DataRedactionSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_redaction_settings' not in self._stubs: + self._stubs['get_data_redaction_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetDataRedactionSettings', + request_serializer=analytics_admin.GetDataRedactionSettingsRequest.serialize, + response_deserializer=resources.DataRedactionSettings.deserialize, + ) + return self._stubs['get_data_redaction_settings'] + + @property + def get_calculated_metric(self) -> Callable[ + [analytics_admin.GetCalculatedMetricRequest], + Awaitable[resources.CalculatedMetric]]: + r"""Return a callable for the get calculated metric method over gRPC. + + Lookup for a single CalculatedMetric. + + Returns: + Callable[[~.GetCalculatedMetricRequest], + Awaitable[~.CalculatedMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_calculated_metric' not in self._stubs: + self._stubs['get_calculated_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetCalculatedMetric', + request_serializer=analytics_admin.GetCalculatedMetricRequest.serialize, + response_deserializer=resources.CalculatedMetric.deserialize, + ) + return self._stubs['get_calculated_metric'] + + @property + def create_calculated_metric(self) -> Callable[ + [analytics_admin.CreateCalculatedMetricRequest], + Awaitable[resources.CalculatedMetric]]: + r"""Return a callable for the create calculated metric method over gRPC. + + Creates a CalculatedMetric. + + Returns: + Callable[[~.CreateCalculatedMetricRequest], + Awaitable[~.CalculatedMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_calculated_metric' not in self._stubs: + self._stubs['create_calculated_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateCalculatedMetric', + request_serializer=analytics_admin.CreateCalculatedMetricRequest.serialize, + response_deserializer=resources.CalculatedMetric.deserialize, + ) + return self._stubs['create_calculated_metric'] + + @property + def list_calculated_metrics(self) -> Callable[ + [analytics_admin.ListCalculatedMetricsRequest], + Awaitable[analytics_admin.ListCalculatedMetricsResponse]]: + r"""Return a callable for the list calculated metrics method over gRPC. + + Lists CalculatedMetrics on a property. + + Returns: + Callable[[~.ListCalculatedMetricsRequest], + Awaitable[~.ListCalculatedMetricsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_calculated_metrics' not in self._stubs: + self._stubs['list_calculated_metrics'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListCalculatedMetrics', + request_serializer=analytics_admin.ListCalculatedMetricsRequest.serialize, + response_deserializer=analytics_admin.ListCalculatedMetricsResponse.deserialize, + ) + return self._stubs['list_calculated_metrics'] + + @property + def update_calculated_metric(self) -> Callable[ + [analytics_admin.UpdateCalculatedMetricRequest], + Awaitable[resources.CalculatedMetric]]: + r"""Return a callable for the update calculated metric method over gRPC. + + Updates a CalculatedMetric on a property. + + Returns: + Callable[[~.UpdateCalculatedMetricRequest], + Awaitable[~.CalculatedMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_calculated_metric' not in self._stubs: + self._stubs['update_calculated_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateCalculatedMetric', + request_serializer=analytics_admin.UpdateCalculatedMetricRequest.serialize, + response_deserializer=resources.CalculatedMetric.deserialize, + ) + return self._stubs['update_calculated_metric'] + + @property + def delete_calculated_metric(self) -> Callable[ + [analytics_admin.DeleteCalculatedMetricRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete calculated metric method over gRPC. + + Deletes a CalculatedMetric on a property. + + Returns: + Callable[[~.DeleteCalculatedMetricRequest], + 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_calculated_metric' not in self._stubs: + self._stubs['delete_calculated_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteCalculatedMetric', + request_serializer=analytics_admin.DeleteCalculatedMetricRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_calculated_metric'] + + @property + def create_rollup_property(self) -> Callable[ + [analytics_admin.CreateRollupPropertyRequest], + Awaitable[analytics_admin.CreateRollupPropertyResponse]]: + r"""Return a callable for the create rollup property method over gRPC. + + Create a roll-up property and all roll-up property + source links. + + Returns: + Callable[[~.CreateRollupPropertyRequest], + Awaitable[~.CreateRollupPropertyResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_rollup_property' not in self._stubs: + self._stubs['create_rollup_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateRollupProperty', + request_serializer=analytics_admin.CreateRollupPropertyRequest.serialize, + response_deserializer=analytics_admin.CreateRollupPropertyResponse.deserialize, + ) + return self._stubs['create_rollup_property'] + + @property + def get_rollup_property_source_link(self) -> Callable[ + [analytics_admin.GetRollupPropertySourceLinkRequest], + Awaitable[resources.RollupPropertySourceLink]]: + r"""Return a callable for the get rollup property source + link method over gRPC. + + Lookup for a single roll-up property source Link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Returns: + Callable[[~.GetRollupPropertySourceLinkRequest], + Awaitable[~.RollupPropertySourceLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_rollup_property_source_link' not in self._stubs: + self._stubs['get_rollup_property_source_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetRollupPropertySourceLink', + request_serializer=analytics_admin.GetRollupPropertySourceLinkRequest.serialize, + response_deserializer=resources.RollupPropertySourceLink.deserialize, + ) + return self._stubs['get_rollup_property_source_link'] + + @property + def list_rollup_property_source_links(self) -> Callable[ + [analytics_admin.ListRollupPropertySourceLinksRequest], + Awaitable[analytics_admin.ListRollupPropertySourceLinksResponse]]: + r"""Return a callable for the list rollup property source + links method over gRPC. + + Lists roll-up property source Links on a property. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Returns: + Callable[[~.ListRollupPropertySourceLinksRequest], + Awaitable[~.ListRollupPropertySourceLinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_rollup_property_source_links' not in self._stubs: + self._stubs['list_rollup_property_source_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListRollupPropertySourceLinks', + request_serializer=analytics_admin.ListRollupPropertySourceLinksRequest.serialize, + response_deserializer=analytics_admin.ListRollupPropertySourceLinksResponse.deserialize, + ) + return self._stubs['list_rollup_property_source_links'] + + @property + def create_rollup_property_source_link(self) -> Callable[ + [analytics_admin.CreateRollupPropertySourceLinkRequest], + Awaitable[resources.RollupPropertySourceLink]]: + r"""Return a callable for the create rollup property source + link method over gRPC. + + Creates a roll-up property source link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Returns: + Callable[[~.CreateRollupPropertySourceLinkRequest], + Awaitable[~.RollupPropertySourceLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_rollup_property_source_link' not in self._stubs: + self._stubs['create_rollup_property_source_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateRollupPropertySourceLink', + request_serializer=analytics_admin.CreateRollupPropertySourceLinkRequest.serialize, + response_deserializer=resources.RollupPropertySourceLink.deserialize, + ) + return self._stubs['create_rollup_property_source_link'] + + @property + def delete_rollup_property_source_link(self) -> Callable[ + [analytics_admin.DeleteRollupPropertySourceLinkRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete rollup property source + link method over gRPC. + + Deletes a roll-up property source link. + Only roll-up properties can have source links, so this + method will throw an error if used on other types of + properties. + + Returns: + Callable[[~.DeleteRollupPropertySourceLinkRequest], + 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_rollup_property_source_link' not in self._stubs: + self._stubs['delete_rollup_property_source_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteRollupPropertySourceLink', + request_serializer=analytics_admin.DeleteRollupPropertySourceLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_rollup_property_source_link'] + + @property + def provision_subproperty(self) -> Callable[ + [analytics_admin.ProvisionSubpropertyRequest], + Awaitable[analytics_admin.ProvisionSubpropertyResponse]]: + r"""Return a callable for the provision subproperty method over gRPC. + + Create a subproperty and a subproperty event filter + that applies to the created subproperty. + + Returns: + Callable[[~.ProvisionSubpropertyRequest], + Awaitable[~.ProvisionSubpropertyResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'provision_subproperty' not in self._stubs: + self._stubs['provision_subproperty'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ProvisionSubproperty', + request_serializer=analytics_admin.ProvisionSubpropertyRequest.serialize, + response_deserializer=analytics_admin.ProvisionSubpropertyResponse.deserialize, + ) + return self._stubs['provision_subproperty'] + + @property + def create_subproperty_event_filter(self) -> Callable[ + [analytics_admin.CreateSubpropertyEventFilterRequest], + Awaitable[gaa_subproperty_event_filter.SubpropertyEventFilter]]: + r"""Return a callable for the create subproperty event + filter method over gRPC. + + Creates a subproperty Event Filter. + + Returns: + Callable[[~.CreateSubpropertyEventFilterRequest], + Awaitable[~.SubpropertyEventFilter]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_subproperty_event_filter' not in self._stubs: + self._stubs['create_subproperty_event_filter'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/CreateSubpropertyEventFilter', + request_serializer=analytics_admin.CreateSubpropertyEventFilterRequest.serialize, + response_deserializer=gaa_subproperty_event_filter.SubpropertyEventFilter.deserialize, + ) + return self._stubs['create_subproperty_event_filter'] + + @property + def get_subproperty_event_filter(self) -> Callable[ + [analytics_admin.GetSubpropertyEventFilterRequest], + Awaitable[subproperty_event_filter.SubpropertyEventFilter]]: + r"""Return a callable for the get subproperty event filter method over gRPC. + + Lookup for a single subproperty Event Filter. + + Returns: + Callable[[~.GetSubpropertyEventFilterRequest], + Awaitable[~.SubpropertyEventFilter]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_subproperty_event_filter' not in self._stubs: + self._stubs['get_subproperty_event_filter'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/GetSubpropertyEventFilter', + request_serializer=analytics_admin.GetSubpropertyEventFilterRequest.serialize, + response_deserializer=subproperty_event_filter.SubpropertyEventFilter.deserialize, + ) + return self._stubs['get_subproperty_event_filter'] + + @property + def list_subproperty_event_filters(self) -> Callable[ + [analytics_admin.ListSubpropertyEventFiltersRequest], + Awaitable[analytics_admin.ListSubpropertyEventFiltersResponse]]: + r"""Return a callable for the list subproperty event filters method over gRPC. + + List all subproperty Event Filters on a property. + + Returns: + Callable[[~.ListSubpropertyEventFiltersRequest], + Awaitable[~.ListSubpropertyEventFiltersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_subproperty_event_filters' not in self._stubs: + self._stubs['list_subproperty_event_filters'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/ListSubpropertyEventFilters', + request_serializer=analytics_admin.ListSubpropertyEventFiltersRequest.serialize, + response_deserializer=analytics_admin.ListSubpropertyEventFiltersResponse.deserialize, + ) + return self._stubs['list_subproperty_event_filters'] + + @property + def update_subproperty_event_filter(self) -> Callable[ + [analytics_admin.UpdateSubpropertyEventFilterRequest], + Awaitable[gaa_subproperty_event_filter.SubpropertyEventFilter]]: + r"""Return a callable for the update subproperty event + filter method over gRPC. + + Updates a subproperty Event Filter. + + Returns: + Callable[[~.UpdateSubpropertyEventFilterRequest], + Awaitable[~.SubpropertyEventFilter]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_subproperty_event_filter' not in self._stubs: + self._stubs['update_subproperty_event_filter'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/UpdateSubpropertyEventFilter', + request_serializer=analytics_admin.UpdateSubpropertyEventFilterRequest.serialize, + response_deserializer=gaa_subproperty_event_filter.SubpropertyEventFilter.deserialize, + ) + return self._stubs['update_subproperty_event_filter'] + + @property + def delete_subproperty_event_filter(self) -> Callable[ + [analytics_admin.DeleteSubpropertyEventFilterRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete subproperty event + filter method over gRPC. + + Deletes a subproperty event filter. + + Returns: + Callable[[~.DeleteSubpropertyEventFilterRequest], + 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_subproperty_event_filter' not in self._stubs: + self._stubs['delete_subproperty_event_filter'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1alpha.AnalyticsAdminService/DeleteSubpropertyEventFilter', + request_serializer=analytics_admin.DeleteSubpropertyEventFilterRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_subproperty_event_filter'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_account: gapic_v1.method_async.wrap_method( + self.get_account, + default_timeout=60.0, + client_info=client_info, + ), + self.list_accounts: gapic_v1.method_async.wrap_method( + self.list_accounts, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_account: gapic_v1.method_async.wrap_method( + self.delete_account, + default_timeout=60.0, + client_info=client_info, + ), + self.update_account: gapic_v1.method_async.wrap_method( + self.update_account, + default_timeout=60.0, + client_info=client_info, + ), + self.provision_account_ticket: gapic_v1.method_async.wrap_method( + self.provision_account_ticket, + default_timeout=60.0, + client_info=client_info, + ), + self.list_account_summaries: gapic_v1.method_async.wrap_method( + self.list_account_summaries, + default_timeout=None, + client_info=client_info, + ), + self.get_property: gapic_v1.method_async.wrap_method( + self.get_property, + default_timeout=60.0, + client_info=client_info, + ), + self.list_properties: gapic_v1.method_async.wrap_method( + self.list_properties, + default_timeout=60.0, + client_info=client_info, + ), + self.create_property: gapic_v1.method_async.wrap_method( + self.create_property, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_property: gapic_v1.method_async.wrap_method( + self.delete_property, + default_timeout=60.0, + client_info=client_info, + ), + self.update_property: gapic_v1.method_async.wrap_method( + self.update_property, + default_timeout=60.0, + client_info=client_info, + ), + self.create_firebase_link: gapic_v1.method_async.wrap_method( + self.create_firebase_link, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_firebase_link: gapic_v1.method_async.wrap_method( + self.delete_firebase_link, + default_timeout=60.0, + client_info=client_info, + ), + self.list_firebase_links: gapic_v1.method_async.wrap_method( + self.list_firebase_links, + default_timeout=60.0, + client_info=client_info, + ), + self.get_global_site_tag: gapic_v1.method_async.wrap_method( + self.get_global_site_tag, + default_timeout=60.0, + client_info=client_info, + ), + self.create_google_ads_link: gapic_v1.method_async.wrap_method( + self.create_google_ads_link, + default_timeout=60.0, + client_info=client_info, + ), + self.update_google_ads_link: gapic_v1.method_async.wrap_method( + self.update_google_ads_link, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_google_ads_link: gapic_v1.method_async.wrap_method( + self.delete_google_ads_link, + default_timeout=60.0, + client_info=client_info, + ), + self.list_google_ads_links: gapic_v1.method_async.wrap_method( + self.list_google_ads_links, + default_timeout=60.0, + client_info=client_info, + ), + self.get_data_sharing_settings: gapic_v1.method_async.wrap_method( + self.get_data_sharing_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_measurement_protocol_secret: gapic_v1.method_async.wrap_method( + self.get_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_measurement_protocol_secrets: gapic_v1.method_async.wrap_method( + self.list_measurement_protocol_secrets, + default_timeout=None, + client_info=client_info, + ), + self.create_measurement_protocol_secret: gapic_v1.method_async.wrap_method( + self.create_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_measurement_protocol_secret: gapic_v1.method_async.wrap_method( + self.delete_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.update_measurement_protocol_secret: gapic_v1.method_async.wrap_method( + self.update_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.acknowledge_user_data_collection: gapic_v1.method_async.wrap_method( + self.acknowledge_user_data_collection, + default_timeout=None, + client_info=client_info, + ), + self.get_sk_ad_network_conversion_value_schema: gapic_v1.method_async.wrap_method( + self.get_sk_ad_network_conversion_value_schema, + default_timeout=None, + client_info=client_info, + ), + self.create_sk_ad_network_conversion_value_schema: gapic_v1.method_async.wrap_method( + self.create_sk_ad_network_conversion_value_schema, + default_timeout=None, + client_info=client_info, + ), + self.delete_sk_ad_network_conversion_value_schema: gapic_v1.method_async.wrap_method( + self.delete_sk_ad_network_conversion_value_schema, + default_timeout=None, + client_info=client_info, + ), + self.update_sk_ad_network_conversion_value_schema: gapic_v1.method_async.wrap_method( + self.update_sk_ad_network_conversion_value_schema, + default_timeout=None, + client_info=client_info, + ), + self.list_sk_ad_network_conversion_value_schemas: gapic_v1.method_async.wrap_method( + self.list_sk_ad_network_conversion_value_schemas, + default_timeout=None, + client_info=client_info, + ), + self.search_change_history_events: gapic_v1.method_async.wrap_method( + self.search_change_history_events, + default_timeout=None, + client_info=client_info, + ), + self.get_google_signals_settings: gapic_v1.method_async.wrap_method( + self.get_google_signals_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_google_signals_settings: gapic_v1.method_async.wrap_method( + self.update_google_signals_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_conversion_event: gapic_v1.method_async.wrap_method( + self.create_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.update_conversion_event: gapic_v1.method_async.wrap_method( + self.update_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.get_conversion_event: gapic_v1.method_async.wrap_method( + self.get_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversion_event: gapic_v1.method_async.wrap_method( + self.delete_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.list_conversion_events: gapic_v1.method_async.wrap_method( + self.list_conversion_events, + default_timeout=None, + client_info=client_info, + ), + self.create_key_event: gapic_v1.method_async.wrap_method( + self.create_key_event, + default_timeout=None, + client_info=client_info, + ), + self.update_key_event: gapic_v1.method_async.wrap_method( + self.update_key_event, + default_timeout=None, + client_info=client_info, + ), + self.get_key_event: gapic_v1.method_async.wrap_method( + self.get_key_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_key_event: gapic_v1.method_async.wrap_method( + self.delete_key_event, + default_timeout=None, + client_info=client_info, + ), + self.list_key_events: gapic_v1.method_async.wrap_method( + self.list_key_events, + default_timeout=None, + client_info=client_info, + ), + self.get_display_video360_advertiser_link: gapic_v1.method_async.wrap_method( + self.get_display_video360_advertiser_link, + default_timeout=None, + client_info=client_info, + ), + self.list_display_video360_advertiser_links: gapic_v1.method_async.wrap_method( + self.list_display_video360_advertiser_links, + default_timeout=None, + client_info=client_info, + ), + self.create_display_video360_advertiser_link: gapic_v1.method_async.wrap_method( + self.create_display_video360_advertiser_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_display_video360_advertiser_link: gapic_v1.method_async.wrap_method( + self.delete_display_video360_advertiser_link, + default_timeout=None, + client_info=client_info, + ), + self.update_display_video360_advertiser_link: gapic_v1.method_async.wrap_method( + self.update_display_video360_advertiser_link, + default_timeout=None, + client_info=client_info, + ), + self.get_display_video360_advertiser_link_proposal: gapic_v1.method_async.wrap_method( + self.get_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.list_display_video360_advertiser_link_proposals: gapic_v1.method_async.wrap_method( + self.list_display_video360_advertiser_link_proposals, + default_timeout=None, + client_info=client_info, + ), + self.create_display_video360_advertiser_link_proposal: gapic_v1.method_async.wrap_method( + self.create_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.delete_display_video360_advertiser_link_proposal: gapic_v1.method_async.wrap_method( + self.delete_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.approve_display_video360_advertiser_link_proposal: gapic_v1.method_async.wrap_method( + self.approve_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.cancel_display_video360_advertiser_link_proposal: gapic_v1.method_async.wrap_method( + self.cancel_display_video360_advertiser_link_proposal, + default_timeout=None, + client_info=client_info, + ), + self.create_custom_dimension: gapic_v1.method_async.wrap_method( + self.create_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.update_custom_dimension: gapic_v1.method_async.wrap_method( + self.update_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.list_custom_dimensions: gapic_v1.method_async.wrap_method( + self.list_custom_dimensions, + default_timeout=None, + client_info=client_info, + ), + self.archive_custom_dimension: gapic_v1.method_async.wrap_method( + self.archive_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.get_custom_dimension: gapic_v1.method_async.wrap_method( + self.get_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.create_custom_metric: gapic_v1.method_async.wrap_method( + self.create_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.update_custom_metric: gapic_v1.method_async.wrap_method( + self.update_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.list_custom_metrics: gapic_v1.method_async.wrap_method( + self.list_custom_metrics, + default_timeout=None, + client_info=client_info, + ), + self.archive_custom_metric: gapic_v1.method_async.wrap_method( + self.archive_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.get_custom_metric: gapic_v1.method_async.wrap_method( + self.get_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.get_data_retention_settings: gapic_v1.method_async.wrap_method( + self.get_data_retention_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_data_retention_settings: gapic_v1.method_async.wrap_method( + self.update_data_retention_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_data_stream: gapic_v1.method_async.wrap_method( + self.create_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_stream: gapic_v1.method_async.wrap_method( + self.delete_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.update_data_stream: gapic_v1.method_async.wrap_method( + self.update_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.list_data_streams: gapic_v1.method_async.wrap_method( + self.list_data_streams, + default_timeout=None, + client_info=client_info, + ), + self.get_data_stream: gapic_v1.method_async.wrap_method( + self.get_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.get_audience: gapic_v1.method_async.wrap_method( + self.get_audience, + default_timeout=None, + client_info=client_info, + ), + self.list_audiences: gapic_v1.method_async.wrap_method( + self.list_audiences, + default_timeout=None, + client_info=client_info, + ), + self.create_audience: gapic_v1.method_async.wrap_method( + self.create_audience, + default_timeout=None, + client_info=client_info, + ), + self.update_audience: gapic_v1.method_async.wrap_method( + self.update_audience, + default_timeout=None, + client_info=client_info, + ), + self.archive_audience: gapic_v1.method_async.wrap_method( + self.archive_audience, + default_timeout=None, + client_info=client_info, + ), + self.get_search_ads360_link: gapic_v1.method_async.wrap_method( + self.get_search_ads360_link, + default_timeout=None, + client_info=client_info, + ), + self.list_search_ads360_links: gapic_v1.method_async.wrap_method( + self.list_search_ads360_links, + default_timeout=None, + client_info=client_info, + ), + self.create_search_ads360_link: gapic_v1.method_async.wrap_method( + self.create_search_ads360_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_search_ads360_link: gapic_v1.method_async.wrap_method( + self.delete_search_ads360_link, + default_timeout=None, + client_info=client_info, + ), + self.update_search_ads360_link: gapic_v1.method_async.wrap_method( + self.update_search_ads360_link, + default_timeout=None, + client_info=client_info, + ), + self.get_attribution_settings: gapic_v1.method_async.wrap_method( + self.get_attribution_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_attribution_settings: gapic_v1.method_async.wrap_method( + self.update_attribution_settings, + default_timeout=None, + client_info=client_info, + ), + self.run_access_report: gapic_v1.method_async.wrap_method( + self.run_access_report, + default_timeout=None, + client_info=client_info, + ), + self.create_access_binding: gapic_v1.method_async.wrap_method( + self.create_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.get_access_binding: gapic_v1.method_async.wrap_method( + self.get_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.update_access_binding: gapic_v1.method_async.wrap_method( + self.update_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.delete_access_binding: gapic_v1.method_async.wrap_method( + self.delete_access_binding, + default_timeout=None, + client_info=client_info, + ), + self.list_access_bindings: gapic_v1.method_async.wrap_method( + self.list_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_access_bindings: gapic_v1.method_async.wrap_method( + self.batch_create_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.batch_get_access_bindings: gapic_v1.method_async.wrap_method( + self.batch_get_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_access_bindings: gapic_v1.method_async.wrap_method( + self.batch_update_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_access_bindings: gapic_v1.method_async.wrap_method( + self.batch_delete_access_bindings, + default_timeout=None, + client_info=client_info, + ), + self.get_expanded_data_set: gapic_v1.method_async.wrap_method( + self.get_expanded_data_set, + default_timeout=None, + client_info=client_info, + ), + self.list_expanded_data_sets: gapic_v1.method_async.wrap_method( + self.list_expanded_data_sets, + default_timeout=None, + client_info=client_info, + ), + self.create_expanded_data_set: gapic_v1.method_async.wrap_method( + self.create_expanded_data_set, + default_timeout=None, + client_info=client_info, + ), + self.update_expanded_data_set: gapic_v1.method_async.wrap_method( + self.update_expanded_data_set, + default_timeout=None, + client_info=client_info, + ), + self.delete_expanded_data_set: gapic_v1.method_async.wrap_method( + self.delete_expanded_data_set, + default_timeout=None, + client_info=client_info, + ), + self.get_channel_group: gapic_v1.method_async.wrap_method( + self.get_channel_group, + default_timeout=None, + client_info=client_info, + ), + self.list_channel_groups: gapic_v1.method_async.wrap_method( + self.list_channel_groups, + default_timeout=None, + client_info=client_info, + ), + self.create_channel_group: gapic_v1.method_async.wrap_method( + self.create_channel_group, + default_timeout=None, + client_info=client_info, + ), + self.update_channel_group: gapic_v1.method_async.wrap_method( + self.update_channel_group, + default_timeout=None, + client_info=client_info, + ), + self.delete_channel_group: gapic_v1.method_async.wrap_method( + self.delete_channel_group, + default_timeout=None, + client_info=client_info, + ), + self.set_automated_ga4_configuration_opt_out: gapic_v1.method_async.wrap_method( + self.set_automated_ga4_configuration_opt_out, + default_timeout=None, + client_info=client_info, + ), + self.fetch_automated_ga4_configuration_opt_out: gapic_v1.method_async.wrap_method( + self.fetch_automated_ga4_configuration_opt_out, + default_timeout=None, + client_info=client_info, + ), + self.create_big_query_link: gapic_v1.method_async.wrap_method( + self.create_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.get_big_query_link: gapic_v1.method_async.wrap_method( + self.get_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.list_big_query_links: gapic_v1.method_async.wrap_method( + self.list_big_query_links, + default_timeout=None, + client_info=client_info, + ), + self.delete_big_query_link: gapic_v1.method_async.wrap_method( + self.delete_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.update_big_query_link: gapic_v1.method_async.wrap_method( + self.update_big_query_link, + default_timeout=None, + client_info=client_info, + ), + self.get_enhanced_measurement_settings: gapic_v1.method_async.wrap_method( + self.get_enhanced_measurement_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.update_enhanced_measurement_settings: gapic_v1.method_async.wrap_method( + self.update_enhanced_measurement_settings, + default_timeout=60.0, + client_info=client_info, + ), + self.create_connected_site_tag: gapic_v1.method_async.wrap_method( + self.create_connected_site_tag, + default_timeout=None, + client_info=client_info, + ), + self.delete_connected_site_tag: gapic_v1.method_async.wrap_method( + self.delete_connected_site_tag, + default_timeout=None, + client_info=client_info, + ), + self.list_connected_site_tags: gapic_v1.method_async.wrap_method( + self.list_connected_site_tags, + default_timeout=None, + client_info=client_info, + ), + self.fetch_connected_ga4_property: gapic_v1.method_async.wrap_method( + self.fetch_connected_ga4_property, + default_timeout=None, + client_info=client_info, + ), + self.get_ad_sense_link: gapic_v1.method_async.wrap_method( + self.get_ad_sense_link, + default_timeout=None, + client_info=client_info, + ), + self.create_ad_sense_link: gapic_v1.method_async.wrap_method( + self.create_ad_sense_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_ad_sense_link: gapic_v1.method_async.wrap_method( + self.delete_ad_sense_link, + default_timeout=None, + client_info=client_info, + ), + self.list_ad_sense_links: gapic_v1.method_async.wrap_method( + self.list_ad_sense_links, + default_timeout=None, + client_info=client_info, + ), + self.get_event_create_rule: gapic_v1.method_async.wrap_method( + self.get_event_create_rule, + default_timeout=None, + client_info=client_info, + ), + self.list_event_create_rules: gapic_v1.method_async.wrap_method( + self.list_event_create_rules, + default_timeout=None, + client_info=client_info, + ), + self.create_event_create_rule: gapic_v1.method_async.wrap_method( + self.create_event_create_rule, + default_timeout=None, + client_info=client_info, + ), + self.update_event_create_rule: gapic_v1.method_async.wrap_method( + self.update_event_create_rule, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_create_rule: gapic_v1.method_async.wrap_method( + self.delete_event_create_rule, + default_timeout=None, + client_info=client_info, + ), + self.get_event_edit_rule: gapic_v1.method_async.wrap_method( + self.get_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.list_event_edit_rules: gapic_v1.method_async.wrap_method( + self.list_event_edit_rules, + default_timeout=None, + client_info=client_info, + ), + self.create_event_edit_rule: gapic_v1.method_async.wrap_method( + self.create_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.update_event_edit_rule: gapic_v1.method_async.wrap_method( + self.update_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.delete_event_edit_rule: gapic_v1.method_async.wrap_method( + self.delete_event_edit_rule, + default_timeout=None, + client_info=client_info, + ), + self.reorder_event_edit_rules: gapic_v1.method_async.wrap_method( + self.reorder_event_edit_rules, + default_timeout=None, + client_info=client_info, + ), + self.update_data_redaction_settings: gapic_v1.method_async.wrap_method( + self.update_data_redaction_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_data_redaction_settings: gapic_v1.method_async.wrap_method( + self.get_data_redaction_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_calculated_metric: gapic_v1.method_async.wrap_method( + self.get_calculated_metric, + default_timeout=None, + client_info=client_info, + ), + self.create_calculated_metric: gapic_v1.method_async.wrap_method( + self.create_calculated_metric, + default_timeout=None, + client_info=client_info, + ), + self.list_calculated_metrics: gapic_v1.method_async.wrap_method( + self.list_calculated_metrics, + default_timeout=None, + client_info=client_info, + ), + self.update_calculated_metric: gapic_v1.method_async.wrap_method( + self.update_calculated_metric, + default_timeout=None, + client_info=client_info, + ), + self.delete_calculated_metric: gapic_v1.method_async.wrap_method( + self.delete_calculated_metric, + default_timeout=None, + client_info=client_info, + ), + self.create_rollup_property: gapic_v1.method_async.wrap_method( + self.create_rollup_property, + default_timeout=None, + client_info=client_info, + ), + self.get_rollup_property_source_link: gapic_v1.method_async.wrap_method( + self.get_rollup_property_source_link, + default_timeout=None, + client_info=client_info, + ), + self.list_rollup_property_source_links: gapic_v1.method_async.wrap_method( + self.list_rollup_property_source_links, + default_timeout=None, + client_info=client_info, + ), + self.create_rollup_property_source_link: gapic_v1.method_async.wrap_method( + self.create_rollup_property_source_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_rollup_property_source_link: gapic_v1.method_async.wrap_method( + self.delete_rollup_property_source_link, + default_timeout=None, + client_info=client_info, + ), + self.provision_subproperty: gapic_v1.method_async.wrap_method( + self.provision_subproperty, + default_timeout=None, + client_info=client_info, + ), + self.create_subproperty_event_filter: gapic_v1.method_async.wrap_method( + self.create_subproperty_event_filter, + default_timeout=None, + client_info=client_info, + ), + self.get_subproperty_event_filter: gapic_v1.method_async.wrap_method( + self.get_subproperty_event_filter, + default_timeout=None, + client_info=client_info, + ), + self.list_subproperty_event_filters: gapic_v1.method_async.wrap_method( + self.list_subproperty_event_filters, + default_timeout=None, + client_info=client_info, + ), + self.update_subproperty_event_filter: gapic_v1.method_async.wrap_method( + self.update_subproperty_event_filter, + default_timeout=None, + client_info=client_info, + ), + self.delete_subproperty_event_filter: gapic_v1.method_async.wrap_method( + self.delete_subproperty_event_filter, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AnalyticsAdminServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/rest.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/rest.py new file mode 100644 index 000000000000..7f4576fe134b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/services/analytics_admin_service/transports/rest.py @@ -0,0 +1,16992 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1alpha.types import analytics_admin +from google.analytics.admin_v1alpha.types import audience +from google.analytics.admin_v1alpha.types import audience as gaa_audience +from google.analytics.admin_v1alpha.types import channel_group +from google.analytics.admin_v1alpha.types import channel_group as gaa_channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set +from google.analytics.admin_v1alpha.types import expanded_data_set as gaa_expanded_data_set +from google.analytics.admin_v1alpha.types import resources +from google.analytics.admin_v1alpha.types import subproperty_event_filter +from google.analytics.admin_v1alpha.types import subproperty_event_filter as gaa_subproperty_event_filter +from google.protobuf import empty_pb2 # type: ignore + +from .base import AnalyticsAdminServiceTransport, 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 AnalyticsAdminServiceRestInterceptor: + """Interceptor for AnalyticsAdminService. + + 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 AnalyticsAdminServiceRestTransport. + + .. code-block:: python + class MyCustomAnalyticsAdminServiceInterceptor(AnalyticsAdminServiceRestInterceptor): + def pre_acknowledge_user_data_collection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_acknowledge_user_data_collection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_approve_display_video360_advertiser_link_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_approve_display_video360_advertiser_link_proposal(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_archive_audience(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_archive_custom_dimension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_archive_custom_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_batch_create_access_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_access_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_delete_access_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_batch_get_access_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_get_access_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_update_access_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_access_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_cancel_display_video360_advertiser_link_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_cancel_display_video360_advertiser_link_proposal(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_access_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_access_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_ad_sense_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_ad_sense_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_audience(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_audience(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_big_query_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_big_query_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_calculated_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_calculated_metric(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_channel_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_channel_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_connected_site_tag(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_connected_site_tag(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_conversion_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_conversion_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_custom_dimension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_dimension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_custom_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_metric(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_data_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_data_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_display_video360_advertiser_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_display_video360_advertiser_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_display_video360_advertiser_link_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_display_video360_advertiser_link_proposal(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_event_create_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_event_create_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_event_edit_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_event_edit_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_expanded_data_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_expanded_data_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_firebase_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_firebase_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_google_ads_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_google_ads_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_key_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_measurement_protocol_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_measurement_protocol_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_property(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_rollup_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_rollup_property(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_rollup_property_source_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_rollup_property_source_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_search_ads360_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_search_ads360_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_sk_ad_network_conversion_value_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sk_ad_network_conversion_value_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_subproperty_event_filter(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_subproperty_event_filter(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_access_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_ad_sense_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_big_query_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_calculated_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_channel_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_connected_site_tag(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_conversion_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_data_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_display_video360_advertiser_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_display_video360_advertiser_link_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_event_create_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_event_edit_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_expanded_data_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_firebase_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_google_ads_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_measurement_protocol_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_property(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_rollup_property_source_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_search_ads360_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_sk_ad_network_conversion_value_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_subproperty_event_filter(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_fetch_automated_ga4_configuration_opt_out(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_automated_ga4_configuration_opt_out(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_connected_ga4_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_connected_ga4_property(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_access_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_access_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_ad_sense_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_ad_sense_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_attribution_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_attribution_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_audience(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_audience(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_big_query_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_big_query_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_calculated_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_calculated_metric(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_channel_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_channel_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_conversion_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_conversion_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_custom_dimension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_dimension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_custom_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_metric(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_redaction_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_redaction_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_retention_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_retention_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_sharing_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_sharing_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_display_video360_advertiser_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_display_video360_advertiser_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_display_video360_advertiser_link_proposal(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_display_video360_advertiser_link_proposal(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_enhanced_measurement_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_enhanced_measurement_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_event_create_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_event_create_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_event_edit_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_event_edit_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_expanded_data_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_expanded_data_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_global_site_tag(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_global_site_tag(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_google_signals_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_google_signals_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_key_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_measurement_protocol_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_measurement_protocol_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_property(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_rollup_property_source_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_rollup_property_source_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_search_ads360_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_search_ads360_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_sk_ad_network_conversion_value_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_sk_ad_network_conversion_value_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_subproperty_event_filter(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_subproperty_event_filter(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_access_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_access_bindings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_accounts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_accounts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_account_summaries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_account_summaries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_ad_sense_links(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_ad_sense_links(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_audiences(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_audiences(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_big_query_links(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_big_query_links(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_calculated_metrics(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_calculated_metrics(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_channel_groups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_channel_groups(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_connected_site_tags(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_connected_site_tags(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_conversion_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_conversion_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_dimensions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_dimensions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_metrics(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_metrics(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_data_streams(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_data_streams(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_display_video360_advertiser_link_proposals(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_display_video360_advertiser_link_proposals(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_display_video360_advertiser_links(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_display_video360_advertiser_links(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_event_create_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_event_create_rules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_event_edit_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_event_edit_rules(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_expanded_data_sets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_expanded_data_sets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_firebase_links(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_firebase_links(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_google_ads_links(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_google_ads_links(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_key_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_key_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_measurement_protocol_secrets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_measurement_protocol_secrets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_properties(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_properties(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_rollup_property_source_links(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_rollup_property_source_links(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_search_ads360_links(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_search_ads360_links(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sk_ad_network_conversion_value_schemas(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sk_ad_network_conversion_value_schemas(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_subproperty_event_filters(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_subproperty_event_filters(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_provision_account_ticket(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_provision_account_ticket(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_provision_subproperty(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_provision_subproperty(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reorder_event_edit_rules(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_run_access_report(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_access_report(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_change_history_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_change_history_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_automated_ga4_configuration_opt_out(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_automated_ga4_configuration_opt_out(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_access_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_access_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_attribution_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_attribution_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_audience(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_audience(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_big_query_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_big_query_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_calculated_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_calculated_metric(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_channel_group(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_channel_group(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_conversion_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_conversion_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_dimension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_dimension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_metric(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_redaction_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_redaction_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_retention_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_retention_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_display_video360_advertiser_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_display_video360_advertiser_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_enhanced_measurement_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_enhanced_measurement_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_event_create_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_event_create_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_event_edit_rule(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_event_edit_rule(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_expanded_data_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_expanded_data_set(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_google_ads_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_google_ads_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_google_signals_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_google_signals_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_key_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_measurement_protocol_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_measurement_protocol_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_property(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_search_ads360_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_search_ads360_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_sk_ad_network_conversion_value_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_sk_ad_network_conversion_value_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_subproperty_event_filter(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_subproperty_event_filter(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AnalyticsAdminServiceRestTransport(interceptor=MyCustomAnalyticsAdminServiceInterceptor()) + client = AnalyticsAdminServiceClient(transport=transport) + + + """ + def pre_acknowledge_user_data_collection(self, request: analytics_admin.AcknowledgeUserDataCollectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.AcknowledgeUserDataCollectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for acknowledge_user_data_collection + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_acknowledge_user_data_collection(self, response: analytics_admin.AcknowledgeUserDataCollectionResponse) -> analytics_admin.AcknowledgeUserDataCollectionResponse: + """Post-rpc interceptor for acknowledge_user_data_collection + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_approve_display_video360_advertiser_link_proposal(self, request: analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for approve_display_video360_advertiser_link_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_approve_display_video360_advertiser_link_proposal(self, response: analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse) -> analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + """Post-rpc interceptor for approve_display_video360_advertiser_link_proposal + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_archive_audience(self, request: analytics_admin.ArchiveAudienceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ArchiveAudienceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for archive_audience + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_archive_custom_dimension(self, request: analytics_admin.ArchiveCustomDimensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ArchiveCustomDimensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for archive_custom_dimension + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_archive_custom_metric(self, request: analytics_admin.ArchiveCustomMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ArchiveCustomMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for archive_custom_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_batch_create_access_bindings(self, request: analytics_admin.BatchCreateAccessBindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.BatchCreateAccessBindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_create_access_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_batch_create_access_bindings(self, response: analytics_admin.BatchCreateAccessBindingsResponse) -> analytics_admin.BatchCreateAccessBindingsResponse: + """Post-rpc interceptor for batch_create_access_bindings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_batch_delete_access_bindings(self, request: analytics_admin.BatchDeleteAccessBindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.BatchDeleteAccessBindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_delete_access_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_batch_get_access_bindings(self, request: analytics_admin.BatchGetAccessBindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.BatchGetAccessBindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_get_access_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_batch_get_access_bindings(self, response: analytics_admin.BatchGetAccessBindingsResponse) -> analytics_admin.BatchGetAccessBindingsResponse: + """Post-rpc interceptor for batch_get_access_bindings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_batch_update_access_bindings(self, request: analytics_admin.BatchUpdateAccessBindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.BatchUpdateAccessBindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_update_access_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_batch_update_access_bindings(self, response: analytics_admin.BatchUpdateAccessBindingsResponse) -> analytics_admin.BatchUpdateAccessBindingsResponse: + """Post-rpc interceptor for batch_update_access_bindings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_cancel_display_video360_advertiser_link_proposal(self, request: analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_display_video360_advertiser_link_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_cancel_display_video360_advertiser_link_proposal(self, response: resources.DisplayVideo360AdvertiserLinkProposal) -> resources.DisplayVideo360AdvertiserLinkProposal: + """Post-rpc interceptor for cancel_display_video360_advertiser_link_proposal + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_access_binding(self, request: analytics_admin.CreateAccessBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateAccessBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_access_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_access_binding(self, response: resources.AccessBinding) -> resources.AccessBinding: + """Post-rpc interceptor for create_access_binding + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_ad_sense_link(self, request: analytics_admin.CreateAdSenseLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateAdSenseLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_ad_sense_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_ad_sense_link(self, response: resources.AdSenseLink) -> resources.AdSenseLink: + """Post-rpc interceptor for create_ad_sense_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_audience(self, request: analytics_admin.CreateAudienceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateAudienceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_audience + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_audience(self, response: gaa_audience.Audience) -> gaa_audience.Audience: + """Post-rpc interceptor for create_audience + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_big_query_link(self, request: analytics_admin.CreateBigQueryLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateBigQueryLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_big_query_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_big_query_link(self, response: resources.BigQueryLink) -> resources.BigQueryLink: + """Post-rpc interceptor for create_big_query_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_calculated_metric(self, request: analytics_admin.CreateCalculatedMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateCalculatedMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_calculated_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_calculated_metric(self, response: resources.CalculatedMetric) -> resources.CalculatedMetric: + """Post-rpc interceptor for create_calculated_metric + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_channel_group(self, request: analytics_admin.CreateChannelGroupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateChannelGroupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_channel_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_channel_group(self, response: gaa_channel_group.ChannelGroup) -> gaa_channel_group.ChannelGroup: + """Post-rpc interceptor for create_channel_group + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_connected_site_tag(self, request: analytics_admin.CreateConnectedSiteTagRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateConnectedSiteTagRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_connected_site_tag + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_connected_site_tag(self, response: analytics_admin.CreateConnectedSiteTagResponse) -> analytics_admin.CreateConnectedSiteTagResponse: + """Post-rpc interceptor for create_connected_site_tag + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_conversion_event(self, request: analytics_admin.CreateConversionEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateConversionEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_conversion_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_conversion_event(self, response: resources.ConversionEvent) -> resources.ConversionEvent: + """Post-rpc interceptor for create_conversion_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_custom_dimension(self, request: analytics_admin.CreateCustomDimensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateCustomDimensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_custom_dimension + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_custom_dimension(self, response: resources.CustomDimension) -> resources.CustomDimension: + """Post-rpc interceptor for create_custom_dimension + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_custom_metric(self, request: analytics_admin.CreateCustomMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateCustomMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_custom_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_custom_metric(self, response: resources.CustomMetric) -> resources.CustomMetric: + """Post-rpc interceptor for create_custom_metric + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_data_stream(self, request: analytics_admin.CreateDataStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateDataStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_data_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_data_stream(self, response: resources.DataStream) -> resources.DataStream: + """Post-rpc interceptor for create_data_stream + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_display_video360_advertiser_link(self, request: analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_display_video360_advertiser_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_display_video360_advertiser_link(self, response: resources.DisplayVideo360AdvertiserLink) -> resources.DisplayVideo360AdvertiserLink: + """Post-rpc interceptor for create_display_video360_advertiser_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_display_video360_advertiser_link_proposal(self, request: analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_display_video360_advertiser_link_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_display_video360_advertiser_link_proposal(self, response: resources.DisplayVideo360AdvertiserLinkProposal) -> resources.DisplayVideo360AdvertiserLinkProposal: + """Post-rpc interceptor for create_display_video360_advertiser_link_proposal + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_event_create_rule(self, request: analytics_admin.CreateEventCreateRuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateEventCreateRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_event_create_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_event_create_rule(self, response: event_create_and_edit.EventCreateRule) -> event_create_and_edit.EventCreateRule: + """Post-rpc interceptor for create_event_create_rule + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_event_edit_rule(self, request: analytics_admin.CreateEventEditRuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateEventEditRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_event_edit_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_event_edit_rule(self, response: event_create_and_edit.EventEditRule) -> event_create_and_edit.EventEditRule: + """Post-rpc interceptor for create_event_edit_rule + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_expanded_data_set(self, request: analytics_admin.CreateExpandedDataSetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateExpandedDataSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_expanded_data_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_expanded_data_set(self, response: gaa_expanded_data_set.ExpandedDataSet) -> gaa_expanded_data_set.ExpandedDataSet: + """Post-rpc interceptor for create_expanded_data_set + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_firebase_link(self, request: analytics_admin.CreateFirebaseLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateFirebaseLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_firebase_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_firebase_link(self, response: resources.FirebaseLink) -> resources.FirebaseLink: + """Post-rpc interceptor for create_firebase_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_google_ads_link(self, request: analytics_admin.CreateGoogleAdsLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateGoogleAdsLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_google_ads_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_google_ads_link(self, response: resources.GoogleAdsLink) -> resources.GoogleAdsLink: + """Post-rpc interceptor for create_google_ads_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_key_event(self, request: analytics_admin.CreateKeyEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_key_event(self, response: resources.KeyEvent) -> resources.KeyEvent: + """Post-rpc interceptor for create_key_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_measurement_protocol_secret(self, request: analytics_admin.CreateMeasurementProtocolSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateMeasurementProtocolSecretRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_measurement_protocol_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_measurement_protocol_secret(self, response: resources.MeasurementProtocolSecret) -> resources.MeasurementProtocolSecret: + """Post-rpc interceptor for create_measurement_protocol_secret + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_property(self, request: analytics_admin.CreatePropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreatePropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_property(self, response: resources.Property) -> resources.Property: + """Post-rpc interceptor for create_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_rollup_property(self, request: analytics_admin.CreateRollupPropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateRollupPropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_rollup_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_rollup_property(self, response: analytics_admin.CreateRollupPropertyResponse) -> analytics_admin.CreateRollupPropertyResponse: + """Post-rpc interceptor for create_rollup_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_rollup_property_source_link(self, request: analytics_admin.CreateRollupPropertySourceLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateRollupPropertySourceLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_rollup_property_source_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_rollup_property_source_link(self, response: resources.RollupPropertySourceLink) -> resources.RollupPropertySourceLink: + """Post-rpc interceptor for create_rollup_property_source_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_search_ads360_link(self, request: analytics_admin.CreateSearchAds360LinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateSearchAds360LinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_search_ads360_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_search_ads360_link(self, response: resources.SearchAds360Link) -> resources.SearchAds360Link: + """Post-rpc interceptor for create_search_ads360_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_sk_ad_network_conversion_value_schema(self, request: analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_sk_ad_network_conversion_value_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_sk_ad_network_conversion_value_schema(self, response: resources.SKAdNetworkConversionValueSchema) -> resources.SKAdNetworkConversionValueSchema: + """Post-rpc interceptor for create_sk_ad_network_conversion_value_schema + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_subproperty_event_filter(self, request: analytics_admin.CreateSubpropertyEventFilterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateSubpropertyEventFilterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_subproperty_event_filter + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_subproperty_event_filter(self, response: gaa_subproperty_event_filter.SubpropertyEventFilter) -> gaa_subproperty_event_filter.SubpropertyEventFilter: + """Post-rpc interceptor for create_subproperty_event_filter + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_delete_access_binding(self, request: analytics_admin.DeleteAccessBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteAccessBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_access_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_account(self, request: analytics_admin.DeleteAccountRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_ad_sense_link(self, request: analytics_admin.DeleteAdSenseLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteAdSenseLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_ad_sense_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_big_query_link(self, request: analytics_admin.DeleteBigQueryLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteBigQueryLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_big_query_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_calculated_metric(self, request: analytics_admin.DeleteCalculatedMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteCalculatedMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_calculated_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_channel_group(self, request: analytics_admin.DeleteChannelGroupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteChannelGroupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_channel_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_connected_site_tag(self, request: analytics_admin.DeleteConnectedSiteTagRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteConnectedSiteTagRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_connected_site_tag + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_conversion_event(self, request: analytics_admin.DeleteConversionEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteConversionEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_conversion_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_data_stream(self, request: analytics_admin.DeleteDataStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteDataStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_data_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_display_video360_advertiser_link(self, request: analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_display_video360_advertiser_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_display_video360_advertiser_link_proposal(self, request: analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_display_video360_advertiser_link_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_event_create_rule(self, request: analytics_admin.DeleteEventCreateRuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteEventCreateRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_event_create_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_event_edit_rule(self, request: analytics_admin.DeleteEventEditRuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteEventEditRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_event_edit_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_expanded_data_set(self, request: analytics_admin.DeleteExpandedDataSetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteExpandedDataSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_expanded_data_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_firebase_link(self, request: analytics_admin.DeleteFirebaseLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteFirebaseLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_firebase_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_google_ads_link(self, request: analytics_admin.DeleteGoogleAdsLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteGoogleAdsLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_google_ads_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_key_event(self, request: analytics_admin.DeleteKeyEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_measurement_protocol_secret(self, request: analytics_admin.DeleteMeasurementProtocolSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteMeasurementProtocolSecretRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_measurement_protocol_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_property(self, request: analytics_admin.DeletePropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeletePropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_delete_property(self, response: resources.Property) -> resources.Property: + """Post-rpc interceptor for delete_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_delete_rollup_property_source_link(self, request: analytics_admin.DeleteRollupPropertySourceLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteRollupPropertySourceLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_rollup_property_source_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_search_ads360_link(self, request: analytics_admin.DeleteSearchAds360LinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteSearchAds360LinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_search_ads360_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_sk_ad_network_conversion_value_schema(self, request: analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_sk_ad_network_conversion_value_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_subproperty_event_filter(self, request: analytics_admin.DeleteSubpropertyEventFilterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteSubpropertyEventFilterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_subproperty_event_filter + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_fetch_automated_ga4_configuration_opt_out(self, request: analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for fetch_automated_ga4_configuration_opt_out + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_fetch_automated_ga4_configuration_opt_out(self, response: analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse) -> analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse: + """Post-rpc interceptor for fetch_automated_ga4_configuration_opt_out + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_fetch_connected_ga4_property(self, request: analytics_admin.FetchConnectedGa4PropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.FetchConnectedGa4PropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for fetch_connected_ga4_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_fetch_connected_ga4_property(self, response: analytics_admin.FetchConnectedGa4PropertyResponse) -> analytics_admin.FetchConnectedGa4PropertyResponse: + """Post-rpc interceptor for fetch_connected_ga4_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_access_binding(self, request: analytics_admin.GetAccessBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetAccessBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_access_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_access_binding(self, response: resources.AccessBinding) -> resources.AccessBinding: + """Post-rpc interceptor for get_access_binding + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_account(self, request: analytics_admin.GetAccountRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_account(self, response: resources.Account) -> resources.Account: + """Post-rpc interceptor for get_account + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_ad_sense_link(self, request: analytics_admin.GetAdSenseLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetAdSenseLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_ad_sense_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_ad_sense_link(self, response: resources.AdSenseLink) -> resources.AdSenseLink: + """Post-rpc interceptor for get_ad_sense_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_attribution_settings(self, request: analytics_admin.GetAttributionSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetAttributionSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_attribution_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_attribution_settings(self, response: resources.AttributionSettings) -> resources.AttributionSettings: + """Post-rpc interceptor for get_attribution_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_audience(self, request: analytics_admin.GetAudienceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetAudienceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_audience + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_audience(self, response: audience.Audience) -> audience.Audience: + """Post-rpc interceptor for get_audience + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_big_query_link(self, request: analytics_admin.GetBigQueryLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetBigQueryLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_big_query_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_big_query_link(self, response: resources.BigQueryLink) -> resources.BigQueryLink: + """Post-rpc interceptor for get_big_query_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_calculated_metric(self, request: analytics_admin.GetCalculatedMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetCalculatedMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_calculated_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_calculated_metric(self, response: resources.CalculatedMetric) -> resources.CalculatedMetric: + """Post-rpc interceptor for get_calculated_metric + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_channel_group(self, request: analytics_admin.GetChannelGroupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetChannelGroupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_channel_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_channel_group(self, response: channel_group.ChannelGroup) -> channel_group.ChannelGroup: + """Post-rpc interceptor for get_channel_group + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_conversion_event(self, request: analytics_admin.GetConversionEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetConversionEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_conversion_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_conversion_event(self, response: resources.ConversionEvent) -> resources.ConversionEvent: + """Post-rpc interceptor for get_conversion_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_custom_dimension(self, request: analytics_admin.GetCustomDimensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetCustomDimensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_custom_dimension + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_custom_dimension(self, response: resources.CustomDimension) -> resources.CustomDimension: + """Post-rpc interceptor for get_custom_dimension + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_custom_metric(self, request: analytics_admin.GetCustomMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetCustomMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_custom_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_custom_metric(self, response: resources.CustomMetric) -> resources.CustomMetric: + """Post-rpc interceptor for get_custom_metric + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_data_redaction_settings(self, request: analytics_admin.GetDataRedactionSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetDataRedactionSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_redaction_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_data_redaction_settings(self, response: resources.DataRedactionSettings) -> resources.DataRedactionSettings: + """Post-rpc interceptor for get_data_redaction_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_data_retention_settings(self, request: analytics_admin.GetDataRetentionSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetDataRetentionSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_retention_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_data_retention_settings(self, response: resources.DataRetentionSettings) -> resources.DataRetentionSettings: + """Post-rpc interceptor for get_data_retention_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_data_sharing_settings(self, request: analytics_admin.GetDataSharingSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetDataSharingSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_sharing_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_data_sharing_settings(self, response: resources.DataSharingSettings) -> resources.DataSharingSettings: + """Post-rpc interceptor for get_data_sharing_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_data_stream(self, request: analytics_admin.GetDataStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetDataStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_data_stream(self, response: resources.DataStream) -> resources.DataStream: + """Post-rpc interceptor for get_data_stream + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_display_video360_advertiser_link(self, request: analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_display_video360_advertiser_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_display_video360_advertiser_link(self, response: resources.DisplayVideo360AdvertiserLink) -> resources.DisplayVideo360AdvertiserLink: + """Post-rpc interceptor for get_display_video360_advertiser_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_display_video360_advertiser_link_proposal(self, request: analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_display_video360_advertiser_link_proposal + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_display_video360_advertiser_link_proposal(self, response: resources.DisplayVideo360AdvertiserLinkProposal) -> resources.DisplayVideo360AdvertiserLinkProposal: + """Post-rpc interceptor for get_display_video360_advertiser_link_proposal + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_enhanced_measurement_settings(self, request: analytics_admin.GetEnhancedMeasurementSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetEnhancedMeasurementSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_enhanced_measurement_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_enhanced_measurement_settings(self, response: resources.EnhancedMeasurementSettings) -> resources.EnhancedMeasurementSettings: + """Post-rpc interceptor for get_enhanced_measurement_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_event_create_rule(self, request: analytics_admin.GetEventCreateRuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetEventCreateRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_event_create_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_event_create_rule(self, response: event_create_and_edit.EventCreateRule) -> event_create_and_edit.EventCreateRule: + """Post-rpc interceptor for get_event_create_rule + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_event_edit_rule(self, request: analytics_admin.GetEventEditRuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetEventEditRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_event_edit_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_event_edit_rule(self, response: event_create_and_edit.EventEditRule) -> event_create_and_edit.EventEditRule: + """Post-rpc interceptor for get_event_edit_rule + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_expanded_data_set(self, request: analytics_admin.GetExpandedDataSetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetExpandedDataSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_expanded_data_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_expanded_data_set(self, response: expanded_data_set.ExpandedDataSet) -> expanded_data_set.ExpandedDataSet: + """Post-rpc interceptor for get_expanded_data_set + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_global_site_tag(self, request: analytics_admin.GetGlobalSiteTagRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetGlobalSiteTagRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_global_site_tag + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_global_site_tag(self, response: resources.GlobalSiteTag) -> resources.GlobalSiteTag: + """Post-rpc interceptor for get_global_site_tag + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_google_signals_settings(self, request: analytics_admin.GetGoogleSignalsSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetGoogleSignalsSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_google_signals_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_google_signals_settings(self, response: resources.GoogleSignalsSettings) -> resources.GoogleSignalsSettings: + """Post-rpc interceptor for get_google_signals_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_key_event(self, request: analytics_admin.GetKeyEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_key_event(self, response: resources.KeyEvent) -> resources.KeyEvent: + """Post-rpc interceptor for get_key_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_measurement_protocol_secret(self, request: analytics_admin.GetMeasurementProtocolSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetMeasurementProtocolSecretRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_measurement_protocol_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_measurement_protocol_secret(self, response: resources.MeasurementProtocolSecret) -> resources.MeasurementProtocolSecret: + """Post-rpc interceptor for get_measurement_protocol_secret + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_property(self, request: analytics_admin.GetPropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetPropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_property(self, response: resources.Property) -> resources.Property: + """Post-rpc interceptor for get_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_rollup_property_source_link(self, request: analytics_admin.GetRollupPropertySourceLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetRollupPropertySourceLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_rollup_property_source_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_rollup_property_source_link(self, response: resources.RollupPropertySourceLink) -> resources.RollupPropertySourceLink: + """Post-rpc interceptor for get_rollup_property_source_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_search_ads360_link(self, request: analytics_admin.GetSearchAds360LinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetSearchAds360LinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_search_ads360_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_search_ads360_link(self, response: resources.SearchAds360Link) -> resources.SearchAds360Link: + """Post-rpc interceptor for get_search_ads360_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_sk_ad_network_conversion_value_schema(self, request: analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_sk_ad_network_conversion_value_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_sk_ad_network_conversion_value_schema(self, response: resources.SKAdNetworkConversionValueSchema) -> resources.SKAdNetworkConversionValueSchema: + """Post-rpc interceptor for get_sk_ad_network_conversion_value_schema + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_subproperty_event_filter(self, request: analytics_admin.GetSubpropertyEventFilterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetSubpropertyEventFilterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_subproperty_event_filter + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_subproperty_event_filter(self, response: subproperty_event_filter.SubpropertyEventFilter) -> subproperty_event_filter.SubpropertyEventFilter: + """Post-rpc interceptor for get_subproperty_event_filter + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_access_bindings(self, request: analytics_admin.ListAccessBindingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListAccessBindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_access_bindings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_access_bindings(self, response: analytics_admin.ListAccessBindingsResponse) -> analytics_admin.ListAccessBindingsResponse: + """Post-rpc interceptor for list_access_bindings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_accounts(self, request: analytics_admin.ListAccountsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListAccountsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_accounts + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_accounts(self, response: analytics_admin.ListAccountsResponse) -> analytics_admin.ListAccountsResponse: + """Post-rpc interceptor for list_accounts + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_account_summaries(self, request: analytics_admin.ListAccountSummariesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListAccountSummariesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_account_summaries + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_account_summaries(self, response: analytics_admin.ListAccountSummariesResponse) -> analytics_admin.ListAccountSummariesResponse: + """Post-rpc interceptor for list_account_summaries + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_ad_sense_links(self, request: analytics_admin.ListAdSenseLinksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListAdSenseLinksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_ad_sense_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_ad_sense_links(self, response: analytics_admin.ListAdSenseLinksResponse) -> analytics_admin.ListAdSenseLinksResponse: + """Post-rpc interceptor for list_ad_sense_links + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_audiences(self, request: analytics_admin.ListAudiencesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListAudiencesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_audiences + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_audiences(self, response: analytics_admin.ListAudiencesResponse) -> analytics_admin.ListAudiencesResponse: + """Post-rpc interceptor for list_audiences + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_big_query_links(self, request: analytics_admin.ListBigQueryLinksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListBigQueryLinksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_big_query_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_big_query_links(self, response: analytics_admin.ListBigQueryLinksResponse) -> analytics_admin.ListBigQueryLinksResponse: + """Post-rpc interceptor for list_big_query_links + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_calculated_metrics(self, request: analytics_admin.ListCalculatedMetricsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListCalculatedMetricsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_calculated_metrics + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_calculated_metrics(self, response: analytics_admin.ListCalculatedMetricsResponse) -> analytics_admin.ListCalculatedMetricsResponse: + """Post-rpc interceptor for list_calculated_metrics + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_channel_groups(self, request: analytics_admin.ListChannelGroupsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListChannelGroupsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_channel_groups + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_channel_groups(self, response: analytics_admin.ListChannelGroupsResponse) -> analytics_admin.ListChannelGroupsResponse: + """Post-rpc interceptor for list_channel_groups + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_connected_site_tags(self, request: analytics_admin.ListConnectedSiteTagsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListConnectedSiteTagsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_connected_site_tags + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_connected_site_tags(self, response: analytics_admin.ListConnectedSiteTagsResponse) -> analytics_admin.ListConnectedSiteTagsResponse: + """Post-rpc interceptor for list_connected_site_tags + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_conversion_events(self, request: analytics_admin.ListConversionEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListConversionEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_conversion_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_conversion_events(self, response: analytics_admin.ListConversionEventsResponse) -> analytics_admin.ListConversionEventsResponse: + """Post-rpc interceptor for list_conversion_events + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_custom_dimensions(self, request: analytics_admin.ListCustomDimensionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListCustomDimensionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_custom_dimensions + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_custom_dimensions(self, response: analytics_admin.ListCustomDimensionsResponse) -> analytics_admin.ListCustomDimensionsResponse: + """Post-rpc interceptor for list_custom_dimensions + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_custom_metrics(self, request: analytics_admin.ListCustomMetricsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListCustomMetricsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_custom_metrics + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_custom_metrics(self, response: analytics_admin.ListCustomMetricsResponse) -> analytics_admin.ListCustomMetricsResponse: + """Post-rpc interceptor for list_custom_metrics + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_data_streams(self, request: analytics_admin.ListDataStreamsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListDataStreamsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_data_streams + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_data_streams(self, response: analytics_admin.ListDataStreamsResponse) -> analytics_admin.ListDataStreamsResponse: + """Post-rpc interceptor for list_data_streams + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_display_video360_advertiser_link_proposals(self, request: analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_display_video360_advertiser_link_proposals + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_display_video360_advertiser_link_proposals(self, response: analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse) -> analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse: + """Post-rpc interceptor for list_display_video360_advertiser_link_proposals + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_display_video360_advertiser_links(self, request: analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_display_video360_advertiser_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_display_video360_advertiser_links(self, response: analytics_admin.ListDisplayVideo360AdvertiserLinksResponse) -> analytics_admin.ListDisplayVideo360AdvertiserLinksResponse: + """Post-rpc interceptor for list_display_video360_advertiser_links + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_event_create_rules(self, request: analytics_admin.ListEventCreateRulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListEventCreateRulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_event_create_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_event_create_rules(self, response: analytics_admin.ListEventCreateRulesResponse) -> analytics_admin.ListEventCreateRulesResponse: + """Post-rpc interceptor for list_event_create_rules + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_event_edit_rules(self, request: analytics_admin.ListEventEditRulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListEventEditRulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_event_edit_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_event_edit_rules(self, response: analytics_admin.ListEventEditRulesResponse) -> analytics_admin.ListEventEditRulesResponse: + """Post-rpc interceptor for list_event_edit_rules + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_expanded_data_sets(self, request: analytics_admin.ListExpandedDataSetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListExpandedDataSetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_expanded_data_sets + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_expanded_data_sets(self, response: analytics_admin.ListExpandedDataSetsResponse) -> analytics_admin.ListExpandedDataSetsResponse: + """Post-rpc interceptor for list_expanded_data_sets + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_firebase_links(self, request: analytics_admin.ListFirebaseLinksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListFirebaseLinksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_firebase_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_firebase_links(self, response: analytics_admin.ListFirebaseLinksResponse) -> analytics_admin.ListFirebaseLinksResponse: + """Post-rpc interceptor for list_firebase_links + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_google_ads_links(self, request: analytics_admin.ListGoogleAdsLinksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListGoogleAdsLinksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_google_ads_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_google_ads_links(self, response: analytics_admin.ListGoogleAdsLinksResponse) -> analytics_admin.ListGoogleAdsLinksResponse: + """Post-rpc interceptor for list_google_ads_links + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_key_events(self, request: analytics_admin.ListKeyEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListKeyEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_key_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_key_events(self, response: analytics_admin.ListKeyEventsResponse) -> analytics_admin.ListKeyEventsResponse: + """Post-rpc interceptor for list_key_events + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_measurement_protocol_secrets(self, request: analytics_admin.ListMeasurementProtocolSecretsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListMeasurementProtocolSecretsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_measurement_protocol_secrets + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_measurement_protocol_secrets(self, response: analytics_admin.ListMeasurementProtocolSecretsResponse) -> analytics_admin.ListMeasurementProtocolSecretsResponse: + """Post-rpc interceptor for list_measurement_protocol_secrets + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_properties(self, request: analytics_admin.ListPropertiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListPropertiesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_properties + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_properties(self, response: analytics_admin.ListPropertiesResponse) -> analytics_admin.ListPropertiesResponse: + """Post-rpc interceptor for list_properties + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_rollup_property_source_links(self, request: analytics_admin.ListRollupPropertySourceLinksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListRollupPropertySourceLinksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_rollup_property_source_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_rollup_property_source_links(self, response: analytics_admin.ListRollupPropertySourceLinksResponse) -> analytics_admin.ListRollupPropertySourceLinksResponse: + """Post-rpc interceptor for list_rollup_property_source_links + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_search_ads360_links(self, request: analytics_admin.ListSearchAds360LinksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListSearchAds360LinksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_search_ads360_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_search_ads360_links(self, response: analytics_admin.ListSearchAds360LinksResponse) -> analytics_admin.ListSearchAds360LinksResponse: + """Post-rpc interceptor for list_search_ads360_links + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_sk_ad_network_conversion_value_schemas(self, request: analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_sk_ad_network_conversion_value_schemas + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_sk_ad_network_conversion_value_schemas(self, response: analytics_admin.ListSKAdNetworkConversionValueSchemasResponse) -> analytics_admin.ListSKAdNetworkConversionValueSchemasResponse: + """Post-rpc interceptor for list_sk_ad_network_conversion_value_schemas + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_subproperty_event_filters(self, request: analytics_admin.ListSubpropertyEventFiltersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListSubpropertyEventFiltersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_subproperty_event_filters + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_subproperty_event_filters(self, response: analytics_admin.ListSubpropertyEventFiltersResponse) -> analytics_admin.ListSubpropertyEventFiltersResponse: + """Post-rpc interceptor for list_subproperty_event_filters + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_provision_account_ticket(self, request: analytics_admin.ProvisionAccountTicketRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ProvisionAccountTicketRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for provision_account_ticket + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_provision_account_ticket(self, response: analytics_admin.ProvisionAccountTicketResponse) -> analytics_admin.ProvisionAccountTicketResponse: + """Post-rpc interceptor for provision_account_ticket + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_provision_subproperty(self, request: analytics_admin.ProvisionSubpropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ProvisionSubpropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for provision_subproperty + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_provision_subproperty(self, response: analytics_admin.ProvisionSubpropertyResponse) -> analytics_admin.ProvisionSubpropertyResponse: + """Post-rpc interceptor for provision_subproperty + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_reorder_event_edit_rules(self, request: analytics_admin.ReorderEventEditRulesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ReorderEventEditRulesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for reorder_event_edit_rules + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_run_access_report(self, request: analytics_admin.RunAccessReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.RunAccessReportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_access_report + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_run_access_report(self, response: analytics_admin.RunAccessReportResponse) -> analytics_admin.RunAccessReportResponse: + """Post-rpc interceptor for run_access_report + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_search_change_history_events(self, request: analytics_admin.SearchChangeHistoryEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.SearchChangeHistoryEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_change_history_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_search_change_history_events(self, response: analytics_admin.SearchChangeHistoryEventsResponse) -> analytics_admin.SearchChangeHistoryEventsResponse: + """Post-rpc interceptor for search_change_history_events + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_set_automated_ga4_configuration_opt_out(self, request: analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_automated_ga4_configuration_opt_out + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_set_automated_ga4_configuration_opt_out(self, response: analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse) -> analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse: + """Post-rpc interceptor for set_automated_ga4_configuration_opt_out + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_access_binding(self, request: analytics_admin.UpdateAccessBindingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateAccessBindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_access_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_access_binding(self, response: resources.AccessBinding) -> resources.AccessBinding: + """Post-rpc interceptor for update_access_binding + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_account(self, request: analytics_admin.UpdateAccountRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_account(self, response: resources.Account) -> resources.Account: + """Post-rpc interceptor for update_account + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_attribution_settings(self, request: analytics_admin.UpdateAttributionSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateAttributionSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_attribution_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_attribution_settings(self, response: resources.AttributionSettings) -> resources.AttributionSettings: + """Post-rpc interceptor for update_attribution_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_audience(self, request: analytics_admin.UpdateAudienceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateAudienceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_audience + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_audience(self, response: gaa_audience.Audience) -> gaa_audience.Audience: + """Post-rpc interceptor for update_audience + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_big_query_link(self, request: analytics_admin.UpdateBigQueryLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateBigQueryLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_big_query_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_big_query_link(self, response: resources.BigQueryLink) -> resources.BigQueryLink: + """Post-rpc interceptor for update_big_query_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_calculated_metric(self, request: analytics_admin.UpdateCalculatedMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateCalculatedMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_calculated_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_calculated_metric(self, response: resources.CalculatedMetric) -> resources.CalculatedMetric: + """Post-rpc interceptor for update_calculated_metric + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_channel_group(self, request: analytics_admin.UpdateChannelGroupRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateChannelGroupRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_channel_group + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_channel_group(self, response: gaa_channel_group.ChannelGroup) -> gaa_channel_group.ChannelGroup: + """Post-rpc interceptor for update_channel_group + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_conversion_event(self, request: analytics_admin.UpdateConversionEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateConversionEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_conversion_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_conversion_event(self, response: resources.ConversionEvent) -> resources.ConversionEvent: + """Post-rpc interceptor for update_conversion_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_custom_dimension(self, request: analytics_admin.UpdateCustomDimensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateCustomDimensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_custom_dimension + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_custom_dimension(self, response: resources.CustomDimension) -> resources.CustomDimension: + """Post-rpc interceptor for update_custom_dimension + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_custom_metric(self, request: analytics_admin.UpdateCustomMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateCustomMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_custom_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_custom_metric(self, response: resources.CustomMetric) -> resources.CustomMetric: + """Post-rpc interceptor for update_custom_metric + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_data_redaction_settings(self, request: analytics_admin.UpdateDataRedactionSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateDataRedactionSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_data_redaction_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_data_redaction_settings(self, response: resources.DataRedactionSettings) -> resources.DataRedactionSettings: + """Post-rpc interceptor for update_data_redaction_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_data_retention_settings(self, request: analytics_admin.UpdateDataRetentionSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateDataRetentionSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_data_retention_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_data_retention_settings(self, response: resources.DataRetentionSettings) -> resources.DataRetentionSettings: + """Post-rpc interceptor for update_data_retention_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_data_stream(self, request: analytics_admin.UpdateDataStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateDataStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_data_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_data_stream(self, response: resources.DataStream) -> resources.DataStream: + """Post-rpc interceptor for update_data_stream + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_display_video360_advertiser_link(self, request: analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_display_video360_advertiser_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_display_video360_advertiser_link(self, response: resources.DisplayVideo360AdvertiserLink) -> resources.DisplayVideo360AdvertiserLink: + """Post-rpc interceptor for update_display_video360_advertiser_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_enhanced_measurement_settings(self, request: analytics_admin.UpdateEnhancedMeasurementSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateEnhancedMeasurementSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_enhanced_measurement_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_enhanced_measurement_settings(self, response: resources.EnhancedMeasurementSettings) -> resources.EnhancedMeasurementSettings: + """Post-rpc interceptor for update_enhanced_measurement_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_event_create_rule(self, request: analytics_admin.UpdateEventCreateRuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateEventCreateRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_event_create_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_event_create_rule(self, response: event_create_and_edit.EventCreateRule) -> event_create_and_edit.EventCreateRule: + """Post-rpc interceptor for update_event_create_rule + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_event_edit_rule(self, request: analytics_admin.UpdateEventEditRuleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateEventEditRuleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_event_edit_rule + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_event_edit_rule(self, response: event_create_and_edit.EventEditRule) -> event_create_and_edit.EventEditRule: + """Post-rpc interceptor for update_event_edit_rule + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_expanded_data_set(self, request: analytics_admin.UpdateExpandedDataSetRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateExpandedDataSetRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_expanded_data_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_expanded_data_set(self, response: gaa_expanded_data_set.ExpandedDataSet) -> gaa_expanded_data_set.ExpandedDataSet: + """Post-rpc interceptor for update_expanded_data_set + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_google_ads_link(self, request: analytics_admin.UpdateGoogleAdsLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateGoogleAdsLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_google_ads_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_google_ads_link(self, response: resources.GoogleAdsLink) -> resources.GoogleAdsLink: + """Post-rpc interceptor for update_google_ads_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_google_signals_settings(self, request: analytics_admin.UpdateGoogleSignalsSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateGoogleSignalsSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_google_signals_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_google_signals_settings(self, response: resources.GoogleSignalsSettings) -> resources.GoogleSignalsSettings: + """Post-rpc interceptor for update_google_signals_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_key_event(self, request: analytics_admin.UpdateKeyEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_key_event(self, response: resources.KeyEvent) -> resources.KeyEvent: + """Post-rpc interceptor for update_key_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_measurement_protocol_secret(self, request: analytics_admin.UpdateMeasurementProtocolSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateMeasurementProtocolSecretRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_measurement_protocol_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_measurement_protocol_secret(self, response: resources.MeasurementProtocolSecret) -> resources.MeasurementProtocolSecret: + """Post-rpc interceptor for update_measurement_protocol_secret + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_property(self, request: analytics_admin.UpdatePropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdatePropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_property(self, response: resources.Property) -> resources.Property: + """Post-rpc interceptor for update_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_search_ads360_link(self, request: analytics_admin.UpdateSearchAds360LinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateSearchAds360LinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_search_ads360_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_search_ads360_link(self, response: resources.SearchAds360Link) -> resources.SearchAds360Link: + """Post-rpc interceptor for update_search_ads360_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_sk_ad_network_conversion_value_schema(self, request: analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_sk_ad_network_conversion_value_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_sk_ad_network_conversion_value_schema(self, response: resources.SKAdNetworkConversionValueSchema) -> resources.SKAdNetworkConversionValueSchema: + """Post-rpc interceptor for update_sk_ad_network_conversion_value_schema + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_subproperty_event_filter(self, request: analytics_admin.UpdateSubpropertyEventFilterRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateSubpropertyEventFilterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_subproperty_event_filter + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_subproperty_event_filter(self, response: gaa_subproperty_event_filter.SubpropertyEventFilter) -> gaa_subproperty_event_filter.SubpropertyEventFilter: + """Post-rpc interceptor for update_subproperty_event_filter + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AnalyticsAdminServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AnalyticsAdminServiceRestInterceptor + + +class AnalyticsAdminServiceRestTransport(AnalyticsAdminServiceTransport): + """REST backend transport for AnalyticsAdminService. + + Service Interface for the Analytics Admin API (GA4). + + 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 = 'analyticsadmin.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[AnalyticsAdminServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'analyticsadmin.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 AnalyticsAdminServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AcknowledgeUserDataCollection(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("AcknowledgeUserDataCollection") + + __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: analytics_admin.AcknowledgeUserDataCollectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.AcknowledgeUserDataCollectionResponse: + r"""Call the acknowledge user data + collection method over HTTP. + + Args: + request (~.analytics_admin.AcknowledgeUserDataCollectionRequest): + The request object. Request message for + AcknowledgeUserDataCollection RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.AcknowledgeUserDataCollectionResponse: + Response message for + AcknowledgeUserDataCollection RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{property=properties/*}:acknowledgeUserDataCollection', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_acknowledge_user_data_collection(request, metadata) + pb_request = analytics_admin.AcknowledgeUserDataCollectionRequest.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 = analytics_admin.AcknowledgeUserDataCollectionResponse() + pb_resp = analytics_admin.AcknowledgeUserDataCollectionResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_acknowledge_user_data_collection(resp) + return resp + + class _ApproveDisplayVideo360AdvertiserLinkProposal(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ApproveDisplayVideo360AdvertiserLinkProposal") + + __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: analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + r"""Call the approve display video360 + advertiser link proposal method over HTTP. + + Args: + request (~.analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest): + The request object. Request message for + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse: + Response message for + ApproveDisplayVideo360AdvertiserLinkProposal + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}:approve', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_approve_display_video360_advertiser_link_proposal(request, metadata) + pb_request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest.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 = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + pb_resp = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_approve_display_video360_advertiser_link_proposal(resp) + return resp + + class _ArchiveAudience(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ArchiveAudience") + + __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: analytics_admin.ArchiveAudienceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the archive audience method over HTTP. + + Args: + request (~.analytics_admin.ArchiveAudienceRequest): + The request object. Request message for ArchiveAudience + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=properties/*/audiences/*}:archive', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_archive_audience(request, metadata) + pb_request = analytics_admin.ArchiveAudienceRequest.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) + + class _ArchiveCustomDimension(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ArchiveCustomDimension") + + __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: analytics_admin.ArchiveCustomDimensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the archive custom dimension method over HTTP. + + Args: + request (~.analytics_admin.ArchiveCustomDimensionRequest): + The request object. Request message for + ArchiveCustomDimension RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=properties/*/customDimensions/*}:archive', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_archive_custom_dimension(request, metadata) + pb_request = analytics_admin.ArchiveCustomDimensionRequest.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) + + class _ArchiveCustomMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ArchiveCustomMetric") + + __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: analytics_admin.ArchiveCustomMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the archive custom metric method over HTTP. + + Args: + request (~.analytics_admin.ArchiveCustomMetricRequest): + The request object. Request message for + ArchiveCustomMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=properties/*/customMetrics/*}:archive', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_archive_custom_metric(request, metadata) + pb_request = analytics_admin.ArchiveCustomMetricRequest.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) + + class _BatchCreateAccessBindings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("BatchCreateAccessBindings") + + __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: analytics_admin.BatchCreateAccessBindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.BatchCreateAccessBindingsResponse: + r"""Call the batch create access + bindings method over HTTP. + + Args: + request (~.analytics_admin.BatchCreateAccessBindingsRequest): + The request object. Request message for + BatchCreateAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.BatchCreateAccessBindingsResponse: + Response message for + BatchCreateAccessBindings RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=accounts/*}/accessBindings:batchCreate', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/accessBindings:batchCreate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_create_access_bindings(request, metadata) + pb_request = analytics_admin.BatchCreateAccessBindingsRequest.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 = analytics_admin.BatchCreateAccessBindingsResponse() + pb_resp = analytics_admin.BatchCreateAccessBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_create_access_bindings(resp) + return resp + + class _BatchDeleteAccessBindings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("BatchDeleteAccessBindings") + + __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: analytics_admin.BatchDeleteAccessBindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the batch delete access + bindings method over HTTP. + + Args: + request (~.analytics_admin.BatchDeleteAccessBindingsRequest): + The request object. Request message for + BatchDeleteAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=accounts/*}/accessBindings:batchDelete', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/accessBindings:batchDelete', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_delete_access_bindings(request, metadata) + pb_request = analytics_admin.BatchDeleteAccessBindingsRequest.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) + + class _BatchGetAccessBindings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("BatchGetAccessBindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "names" : "", } + + @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: analytics_admin.BatchGetAccessBindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.BatchGetAccessBindingsResponse: + r"""Call the batch get access bindings method over HTTP. + + Args: + request (~.analytics_admin.BatchGetAccessBindingsRequest): + The request object. Request message for + BatchGetAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.BatchGetAccessBindingsResponse: + Response message for + BatchGetAccessBindings RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=accounts/*}/accessBindings:batchGet', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/accessBindings:batchGet', + }, + ] + request, metadata = self._interceptor.pre_batch_get_access_bindings(request, metadata) + pb_request = analytics_admin.BatchGetAccessBindingsRequest.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 = analytics_admin.BatchGetAccessBindingsResponse() + pb_resp = analytics_admin.BatchGetAccessBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_get_access_bindings(resp) + return resp + + class _BatchUpdateAccessBindings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("BatchUpdateAccessBindings") + + __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: analytics_admin.BatchUpdateAccessBindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.BatchUpdateAccessBindingsResponse: + r"""Call the batch update access + bindings method over HTTP. + + Args: + request (~.analytics_admin.BatchUpdateAccessBindingsRequest): + The request object. Request message for + BatchUpdateAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.BatchUpdateAccessBindingsResponse: + Response message for + BatchUpdateAccessBindings RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=accounts/*}/accessBindings:batchUpdate', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/accessBindings:batchUpdate', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_batch_update_access_bindings(request, metadata) + pb_request = analytics_admin.BatchUpdateAccessBindingsRequest.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 = analytics_admin.BatchUpdateAccessBindingsResponse() + pb_resp = analytics_admin.BatchUpdateAccessBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_update_access_bindings(resp) + return resp + + class _CancelDisplayVideo360AdvertiserLinkProposal(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CancelDisplayVideo360AdvertiserLinkProposal") + + __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: analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Call the cancel display video360 + advertiser link proposal method over HTTP. + + Args: + request (~.analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest): + The request object. Request message for + CancelDisplayVideo360AdvertiserLinkProposal + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}:cancel', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_cancel_display_video360_advertiser_link_proposal(request, metadata) + pb_request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest.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 = resources.DisplayVideo360AdvertiserLinkProposal() + pb_resp = resources.DisplayVideo360AdvertiserLinkProposal.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_cancel_display_video360_advertiser_link_proposal(resp) + return resp + + class _CreateAccessBinding(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateAccessBinding") + + __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: analytics_admin.CreateAccessBindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.AccessBinding: + r"""Call the create access binding method over HTTP. + + Args: + request (~.analytics_admin.CreateAccessBindingRequest): + The request object. Request message for + CreateAccessBinding RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.AccessBinding: + A binding of a user to a set of + roles. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=accounts/*}/accessBindings', + 'body': 'access_binding', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/accessBindings', + 'body': 'access_binding', + }, + ] + request, metadata = self._interceptor.pre_create_access_binding(request, metadata) + pb_request = analytics_admin.CreateAccessBindingRequest.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 = resources.AccessBinding() + pb_resp = resources.AccessBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_access_binding(resp) + return resp + + class _CreateAdSenseLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateAdSenseLink") + + __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: analytics_admin.CreateAdSenseLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.AdSenseLink: + r"""Call the create ad sense link method over HTTP. + + Args: + request (~.analytics_admin.CreateAdSenseLinkRequest): + The request object. Request message to be passed to + CreateAdSenseLink method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/adSenseLinks', + 'body': 'adsense_link', + }, + ] + request, metadata = self._interceptor.pre_create_ad_sense_link(request, metadata) + pb_request = analytics_admin.CreateAdSenseLinkRequest.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 = resources.AdSenseLink() + pb_resp = resources.AdSenseLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_ad_sense_link(resp) + return resp + + class _CreateAudience(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateAudience") + + __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: analytics_admin.CreateAudienceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gaa_audience.Audience: + r"""Call the create audience method over HTTP. + + Args: + request (~.analytics_admin.CreateAudienceRequest): + The request object. Request message for CreateAudience + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gaa_audience.Audience: + A resource message representing a GA4 + Audience. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/audiences', + 'body': 'audience', + }, + ] + request, metadata = self._interceptor.pre_create_audience(request, metadata) + pb_request = analytics_admin.CreateAudienceRequest.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 = gaa_audience.Audience() + pb_resp = gaa_audience.Audience.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_audience(resp) + return resp + + class _CreateBigQueryLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateBigQueryLink") + + __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: analytics_admin.CreateBigQueryLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.BigQueryLink: + r"""Call the create big query link method over HTTP. + + Args: + request (~.analytics_admin.CreateBigQueryLinkRequest): + The request object. Request message for + CreateBigQueryLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/bigQueryLinks', + 'body': 'bigquery_link', + }, + ] + request, metadata = self._interceptor.pre_create_big_query_link(request, metadata) + pb_request = analytics_admin.CreateBigQueryLinkRequest.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 = resources.BigQueryLink() + pb_resp = resources.BigQueryLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_big_query_link(resp) + return resp + + class _CreateCalculatedMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateCalculatedMetric") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "calculatedMetricId" : "", } + + @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: analytics_admin.CreateCalculatedMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CalculatedMetric: + r"""Call the create calculated metric method over HTTP. + + Args: + request (~.analytics_admin.CreateCalculatedMetricRequest): + The request object. Request message for + CreateCalculatedMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CalculatedMetric: + A definition for a calculated metric. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/calculatedMetrics', + 'body': 'calculated_metric', + }, + ] + request, metadata = self._interceptor.pre_create_calculated_metric(request, metadata) + pb_request = analytics_admin.CreateCalculatedMetricRequest.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 = resources.CalculatedMetric() + pb_resp = resources.CalculatedMetric.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_calculated_metric(resp) + return resp + + class _CreateChannelGroup(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateChannelGroup") + + __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: analytics_admin.CreateChannelGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gaa_channel_group.ChannelGroup: + r"""Call the create channel group method over HTTP. + + Args: + request (~.analytics_admin.CreateChannelGroupRequest): + The request object. Request message for + CreateChannelGroup RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gaa_channel_group.ChannelGroup: + A resource message representing a + Channel Group. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/channelGroups', + 'body': 'channel_group', + }, + ] + request, metadata = self._interceptor.pre_create_channel_group(request, metadata) + pb_request = analytics_admin.CreateChannelGroupRequest.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 = gaa_channel_group.ChannelGroup() + pb_resp = gaa_channel_group.ChannelGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_channel_group(resp) + return resp + + class _CreateConnectedSiteTag(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateConnectedSiteTag") + + __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: analytics_admin.CreateConnectedSiteTagRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.CreateConnectedSiteTagResponse: + r"""Call the create connected site tag method over HTTP. + + Args: + request (~.analytics_admin.CreateConnectedSiteTagRequest): + The request object. Request message for + CreateConnectedSiteTag RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.CreateConnectedSiteTagResponse: + Response message for + CreateConnectedSiteTag RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/properties:createConnectedSiteTag', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_create_connected_site_tag(request, metadata) + pb_request = analytics_admin.CreateConnectedSiteTagRequest.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 = analytics_admin.CreateConnectedSiteTagResponse() + pb_resp = analytics_admin.CreateConnectedSiteTagResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_connected_site_tag(resp) + return resp + + class _CreateConversionEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateConversionEvent") + + __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: analytics_admin.CreateConversionEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ConversionEvent: + r"""Call the create conversion event method over HTTP. + + Args: + request (~.analytics_admin.CreateConversionEventRequest): + The request object. Request message for + CreateConversionEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/conversionEvents', + 'body': 'conversion_event', + }, + ] + request, metadata = self._interceptor.pre_create_conversion_event(request, metadata) + pb_request = analytics_admin.CreateConversionEventRequest.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 = resources.ConversionEvent() + pb_resp = resources.ConversionEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_conversion_event(resp) + return resp + + class _CreateCustomDimension(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateCustomDimension") + + __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: analytics_admin.CreateCustomDimensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomDimension: + r"""Call the create custom dimension method over HTTP. + + Args: + request (~.analytics_admin.CreateCustomDimensionRequest): + The request object. Request message for + CreateCustomDimension RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomDimension: + A definition for a CustomDimension. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/customDimensions', + 'body': 'custom_dimension', + }, + ] + request, metadata = self._interceptor.pre_create_custom_dimension(request, metadata) + pb_request = analytics_admin.CreateCustomDimensionRequest.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 = resources.CustomDimension() + pb_resp = resources.CustomDimension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_custom_dimension(resp) + return resp + + class _CreateCustomMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateCustomMetric") + + __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: analytics_admin.CreateCustomMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomMetric: + r"""Call the create custom metric method over HTTP. + + Args: + request (~.analytics_admin.CreateCustomMetricRequest): + The request object. Request message for + CreateCustomMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomMetric: + A definition for a custom metric. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/customMetrics', + 'body': 'custom_metric', + }, + ] + request, metadata = self._interceptor.pre_create_custom_metric(request, metadata) + pb_request = analytics_admin.CreateCustomMetricRequest.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 = resources.CustomMetric() + pb_resp = resources.CustomMetric.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_custom_metric(resp) + return resp + + class _CreateDataStream(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateDataStream") + + __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: analytics_admin.CreateDataStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataStream: + r"""Call the create data stream method over HTTP. + + Args: + request (~.analytics_admin.CreateDataStreamRequest): + The request object. Request message for CreateDataStream + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataStream: + A resource message representing a + data stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/dataStreams', + 'body': 'data_stream', + }, + ] + request, metadata = self._interceptor.pre_create_data_stream(request, metadata) + pb_request = analytics_admin.CreateDataStreamRequest.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 = resources.DataStream() + pb_resp = resources.DataStream.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_data_stream(resp) + return resp + + class _CreateDisplayVideo360AdvertiserLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateDisplayVideo360AdvertiserLink") + + __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: analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Call the create display video360 + advertiser link method over HTTP. + + Args: + request (~.analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest): + The request object. Request message for + CreateDisplayVideo360AdvertiserLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinks', + 'body': 'display_video_360_advertiser_link', + }, + ] + request, metadata = self._interceptor.pre_create_display_video360_advertiser_link(request, metadata) + pb_request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest.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 = resources.DisplayVideo360AdvertiserLink() + pb_resp = resources.DisplayVideo360AdvertiserLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_display_video360_advertiser_link(resp) + return resp + + class _CreateDisplayVideo360AdvertiserLinkProposal(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateDisplayVideo360AdvertiserLinkProposal") + + __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: analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Call the create display video360 + advertiser link proposal method over HTTP. + + Args: + request (~.analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest): + The request object. Request message for + CreateDisplayVideo360AdvertiserLinkProposal + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinkProposals', + 'body': 'display_video_360_advertiser_link_proposal', + }, + ] + request, metadata = self._interceptor.pre_create_display_video360_advertiser_link_proposal(request, metadata) + pb_request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest.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 = resources.DisplayVideo360AdvertiserLinkProposal() + pb_resp = resources.DisplayVideo360AdvertiserLinkProposal.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_display_video360_advertiser_link_proposal(resp) + return resp + + class _CreateEventCreateRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateEventCreateRule") + + __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: analytics_admin.CreateEventCreateRuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> event_create_and_edit.EventCreateRule: + r"""Call the create event create rule method over HTTP. + + Args: + request (~.analytics_admin.CreateEventCreateRuleRequest): + The request object. Request message for + CreateEventCreateRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_create_and_edit.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*/dataStreams/*}/eventCreateRules', + 'body': 'event_create_rule', + }, + ] + request, metadata = self._interceptor.pre_create_event_create_rule(request, metadata) + pb_request = analytics_admin.CreateEventCreateRuleRequest.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 = event_create_and_edit.EventCreateRule() + pb_resp = event_create_and_edit.EventCreateRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_event_create_rule(resp) + return resp + + class _CreateEventEditRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateEventEditRule") + + __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: analytics_admin.CreateEventEditRuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> event_create_and_edit.EventEditRule: + r"""Call the create event edit rule method over HTTP. + + Args: + request (~.analytics_admin.CreateEventEditRuleRequest): + The request object. Request message for + CreateEventEditRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_create_and_edit.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules', + 'body': 'event_edit_rule', + }, + ] + request, metadata = self._interceptor.pre_create_event_edit_rule(request, metadata) + pb_request = analytics_admin.CreateEventEditRuleRequest.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 = event_create_and_edit.EventEditRule() + pb_resp = event_create_and_edit.EventEditRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_event_edit_rule(resp) + return resp + + class _CreateExpandedDataSet(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateExpandedDataSet") + + __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: analytics_admin.CreateExpandedDataSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Call the create expanded data set method over HTTP. + + Args: + request (~.analytics_admin.CreateExpandedDataSetRequest): + The request object. Request message for + CreateExpandedDataSet RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gaa_expanded_data_set.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/expandedDataSets', + 'body': 'expanded_data_set', + }, + ] + request, metadata = self._interceptor.pre_create_expanded_data_set(request, metadata) + pb_request = analytics_admin.CreateExpandedDataSetRequest.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 = gaa_expanded_data_set.ExpandedDataSet() + pb_resp = gaa_expanded_data_set.ExpandedDataSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_expanded_data_set(resp) + return resp + + class _CreateFirebaseLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateFirebaseLink") + + __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: analytics_admin.CreateFirebaseLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.FirebaseLink: + r"""Call the create firebase link method over HTTP. + + Args: + request (~.analytics_admin.CreateFirebaseLinkRequest): + The request object. Request message for + CreateFirebaseLink RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.FirebaseLink: + A link between a GA4 property and a + Firebase project. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/firebaseLinks', + 'body': 'firebase_link', + }, + ] + request, metadata = self._interceptor.pre_create_firebase_link(request, metadata) + pb_request = analytics_admin.CreateFirebaseLinkRequest.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 = resources.FirebaseLink() + pb_resp = resources.FirebaseLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_firebase_link(resp) + return resp + + class _CreateGoogleAdsLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateGoogleAdsLink") + + __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: analytics_admin.CreateGoogleAdsLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.GoogleAdsLink: + r"""Call the create google ads link method over HTTP. + + Args: + request (~.analytics_admin.CreateGoogleAdsLinkRequest): + The request object. Request message for + CreateGoogleAdsLink RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/googleAdsLinks', + 'body': 'google_ads_link', + }, + ] + request, metadata = self._interceptor.pre_create_google_ads_link(request, metadata) + pb_request = analytics_admin.CreateGoogleAdsLinkRequest.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 = resources.GoogleAdsLink() + pb_resp = resources.GoogleAdsLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_google_ads_link(resp) + return resp + + class _CreateKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateKeyEvent") + + __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: analytics_admin.CreateKeyEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.KeyEvent: + r"""Call the create key event method over HTTP. + + Args: + request (~.analytics_admin.CreateKeyEventRequest): + The request object. Request message for CreateKeyEvent + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.KeyEvent: + A key event in a Google Analytics + property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/keyEvents', + 'body': 'key_event', + }, + ] + request, metadata = self._interceptor.pre_create_key_event(request, metadata) + pb_request = analytics_admin.CreateKeyEventRequest.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 = resources.KeyEvent() + pb_resp = resources.KeyEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_key_event(resp) + return resp + + class _CreateMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateMeasurementProtocolSecret") + + __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: analytics_admin.CreateMeasurementProtocolSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.MeasurementProtocolSecret: + r"""Call the create measurement + protocol secret method over HTTP. + + Args: + request (~.analytics_admin.CreateMeasurementProtocolSecretRequest): + The request object. Request message for + CreateMeasurementProtocolSecret RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets', + 'body': 'measurement_protocol_secret', + }, + ] + request, metadata = self._interceptor.pre_create_measurement_protocol_secret(request, metadata) + pb_request = analytics_admin.CreateMeasurementProtocolSecretRequest.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 = resources.MeasurementProtocolSecret() + pb_resp = resources.MeasurementProtocolSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_measurement_protocol_secret(resp) + return resp + + class _CreateProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateProperty") + + __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: analytics_admin.CreatePropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Property: + r"""Call the create property method over HTTP. + + Args: + request (~.analytics_admin.CreatePropertyRequest): + The request object. Request message for CreateProperty + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/properties', + 'body': 'property', + }, + ] + request, metadata = self._interceptor.pre_create_property(request, metadata) + pb_request = analytics_admin.CreatePropertyRequest.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 = resources.Property() + pb_resp = resources.Property.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_property(resp) + return resp + + class _CreateRollupProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateRollupProperty") + + __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: analytics_admin.CreateRollupPropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.CreateRollupPropertyResponse: + r"""Call the create rollup property method over HTTP. + + Args: + request (~.analytics_admin.CreateRollupPropertyRequest): + The request object. Request message for + CreateRollupProperty RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.CreateRollupPropertyResponse: + Response message for + CreateRollupProperty RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/properties:createRollupProperty', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_create_rollup_property(request, metadata) + pb_request = analytics_admin.CreateRollupPropertyRequest.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 = analytics_admin.CreateRollupPropertyResponse() + pb_resp = analytics_admin.CreateRollupPropertyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_rollup_property(resp) + return resp + + class _CreateRollupPropertySourceLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateRollupPropertySourceLink") + + __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: analytics_admin.CreateRollupPropertySourceLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.RollupPropertySourceLink: + r"""Call the create rollup property + source link method over HTTP. + + Args: + request (~.analytics_admin.CreateRollupPropertySourceLinkRequest): + The request object. Request message for + CreateRollupPropertySourceLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.RollupPropertySourceLink: + A link that references a source + property under the parent rollup + property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/rollupPropertySourceLinks', + 'body': 'rollup_property_source_link', + }, + ] + request, metadata = self._interceptor.pre_create_rollup_property_source_link(request, metadata) + pb_request = analytics_admin.CreateRollupPropertySourceLinkRequest.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 = resources.RollupPropertySourceLink() + pb_resp = resources.RollupPropertySourceLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_rollup_property_source_link(resp) + return resp + + class _CreateSearchAds360Link(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateSearchAds360Link") + + __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: analytics_admin.CreateSearchAds360LinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.SearchAds360Link: + r"""Call the create search ads360 link method over HTTP. + + Args: + request (~.analytics_admin.CreateSearchAds360LinkRequest): + The request object. Request message for + CreateSearchAds360Link RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/searchAds360Links', + 'body': 'search_ads_360_link', + }, + ] + request, metadata = self._interceptor.pre_create_search_ads360_link(request, metadata) + pb_request = analytics_admin.CreateSearchAds360LinkRequest.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 = resources.SearchAds360Link() + pb_resp = resources.SearchAds360Link.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_search_ads360_link(resp) + return resp + + class _CreateSKAdNetworkConversionValueSchema(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateSKAdNetworkConversionValueSchema") + + __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: analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.SKAdNetworkConversionValueSchema: + r"""Call the create sk ad network + conversion value schema method over HTTP. + + Args: + request (~.analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest): + The request object. Request message for + CreateSKAdNetworkConversionValueSchema + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SKAdNetworkConversionValueSchema: + SKAdNetwork conversion value schema + of an iOS stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*/dataStreams/*}/sKAdNetworkConversionValueSchema', + 'body': 'skadnetwork_conversion_value_schema', + }, + ] + request, metadata = self._interceptor.pre_create_sk_ad_network_conversion_value_schema(request, metadata) + pb_request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest.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 = resources.SKAdNetworkConversionValueSchema() + pb_resp = resources.SKAdNetworkConversionValueSchema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_sk_ad_network_conversion_value_schema(resp) + return resp + + class _CreateSubpropertyEventFilter(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateSubpropertyEventFilter") + + __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: analytics_admin.CreateSubpropertyEventFilterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gaa_subproperty_event_filter.SubpropertyEventFilter: + r"""Call the create subproperty event + filter method over HTTP. + + Args: + request (~.analytics_admin.CreateSubpropertyEventFilterRequest): + The request object. Request message for + CreateSubpropertyEventFilter RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gaa_subproperty_event_filter.SubpropertyEventFilter: + A resource message representing a GA4 + Subproperty event filter. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*}/subpropertyEventFilters', + 'body': 'subproperty_event_filter', + }, + ] + request, metadata = self._interceptor.pre_create_subproperty_event_filter(request, metadata) + pb_request = analytics_admin.CreateSubpropertyEventFilterRequest.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 = gaa_subproperty_event_filter.SubpropertyEventFilter() + pb_resp = gaa_subproperty_event_filter.SubpropertyEventFilter.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_subproperty_event_filter(resp) + return resp + + class _DeleteAccessBinding(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteAccessBinding") + + __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: analytics_admin.DeleteAccessBindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete access binding method over HTTP. + + Args: + request (~.analytics_admin.DeleteAccessBindingRequest): + The request object. Request message for + DeleteAccessBinding RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=accounts/*/accessBindings/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1alpha/{name=properties/*/accessBindings/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_access_binding(request, metadata) + pb_request = analytics_admin.DeleteAccessBindingRequest.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 _DeleteAccount(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteAccount") + + __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: analytics_admin.DeleteAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete account method over HTTP. + + Args: + request (~.analytics_admin.DeleteAccountRequest): + The request object. Request message for DeleteAccount + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=accounts/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_account(request, metadata) + pb_request = analytics_admin.DeleteAccountRequest.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 _DeleteAdSenseLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteAdSenseLink") + + __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: analytics_admin.DeleteAdSenseLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete ad sense link method over HTTP. + + Args: + request (~.analytics_admin.DeleteAdSenseLinkRequest): + The request object. Request message to be passed to + DeleteAdSenseLink method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=properties/*/adSenseLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_ad_sense_link(request, metadata) + pb_request = analytics_admin.DeleteAdSenseLinkRequest.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 _DeleteBigQueryLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteBigQueryLink") + + __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: analytics_admin.DeleteBigQueryLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete big query link method over HTTP. + + Args: + request (~.analytics_admin.DeleteBigQueryLinkRequest): + The request object. Request message for + DeleteBigQueryLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/bigQueryLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_big_query_link(request, metadata) + pb_request = analytics_admin.DeleteBigQueryLinkRequest.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 _DeleteCalculatedMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteCalculatedMetric") + + __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: analytics_admin.DeleteCalculatedMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete calculated metric method over HTTP. + + Args: + request (~.analytics_admin.DeleteCalculatedMetricRequest): + The request object. Request message for + DeleteCalculatedMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/calculatedMetrics/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_calculated_metric(request, metadata) + pb_request = analytics_admin.DeleteCalculatedMetricRequest.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 _DeleteChannelGroup(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteChannelGroup") + + __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: analytics_admin.DeleteChannelGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete channel group method over HTTP. + + Args: + request (~.analytics_admin.DeleteChannelGroupRequest): + The request object. Request message for + DeleteChannelGroup RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/channelGroups/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_channel_group(request, metadata) + pb_request = analytics_admin.DeleteChannelGroupRequest.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 _DeleteConnectedSiteTag(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteConnectedSiteTag") + + def __call__(self, + request: analytics_admin.DeleteConnectedSiteTagRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete connected site tag method over HTTP. + + Args: + request (~.analytics_admin.DeleteConnectedSiteTagRequest): + The request object. Request message for + DeleteConnectedSiteTag RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/properties:deleteConnectedSiteTag', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_delete_connected_site_tag(request, metadata) + pb_request = analytics_admin.DeleteConnectedSiteTagRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteConversionEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteConversionEvent") + + __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: analytics_admin.DeleteConversionEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete conversion event method over HTTP. + + Args: + request (~.analytics_admin.DeleteConversionEventRequest): + The request object. Request message for + DeleteConversionEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/conversionEvents/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_conversion_event(request, metadata) + pb_request = analytics_admin.DeleteConversionEventRequest.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 _DeleteDataStream(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteDataStream") + + __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: analytics_admin.DeleteDataStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete data stream method over HTTP. + + Args: + request (~.analytics_admin.DeleteDataStreamRequest): + The request object. Request message for DeleteDataStream + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/dataStreams/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_data_stream(request, metadata) + pb_request = analytics_admin.DeleteDataStreamRequest.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 _DeleteDisplayVideo360AdvertiserLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteDisplayVideo360AdvertiserLink") + + __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: analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete display video360 + advertiser link method over HTTP. + + Args: + request (~.analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest): + The request object. Request message for + DeleteDisplayVideo360AdvertiserLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/displayVideo360AdvertiserLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_display_video360_advertiser_link(request, metadata) + pb_request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest.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 _DeleteDisplayVideo360AdvertiserLinkProposal(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteDisplayVideo360AdvertiserLinkProposal") + + __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: analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete display video360 + advertiser link proposal method over HTTP. + + Args: + request (~.analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest): + The request object. Request message for + DeleteDisplayVideo360AdvertiserLinkProposal + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_display_video360_advertiser_link_proposal(request, metadata) + pb_request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest.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 _DeleteEventCreateRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteEventCreateRule") + + __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: analytics_admin.DeleteEventCreateRuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete event create rule method over HTTP. + + Args: + request (~.analytics_admin.DeleteEventCreateRuleRequest): + The request object. Request message for + DeleteEventCreateRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/dataStreams/*/eventCreateRules/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_event_create_rule(request, metadata) + pb_request = analytics_admin.DeleteEventCreateRuleRequest.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 _DeleteEventEditRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteEventEditRule") + + __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: analytics_admin.DeleteEventEditRuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete event edit rule method over HTTP. + + Args: + request (~.analytics_admin.DeleteEventEditRuleRequest): + The request object. Request message for + DeleteEventEditRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/dataStreams/*/eventEditRules/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_event_edit_rule(request, metadata) + pb_request = analytics_admin.DeleteEventEditRuleRequest.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 _DeleteExpandedDataSet(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteExpandedDataSet") + + __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: analytics_admin.DeleteExpandedDataSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete expanded data set method over HTTP. + + Args: + request (~.analytics_admin.DeleteExpandedDataSetRequest): + The request object. Request message for + DeleteExpandedDataSet RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/expandedDataSets/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_expanded_data_set(request, metadata) + pb_request = analytics_admin.DeleteExpandedDataSetRequest.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 _DeleteFirebaseLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteFirebaseLink") + + __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: analytics_admin.DeleteFirebaseLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete firebase link method over HTTP. + + Args: + request (~.analytics_admin.DeleteFirebaseLinkRequest): + The request object. Request message for + DeleteFirebaseLink RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/firebaseLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_firebase_link(request, metadata) + pb_request = analytics_admin.DeleteFirebaseLinkRequest.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 _DeleteGoogleAdsLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteGoogleAdsLink") + + __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: analytics_admin.DeleteGoogleAdsLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete google ads link method over HTTP. + + Args: + request (~.analytics_admin.DeleteGoogleAdsLinkRequest): + The request object. Request message for + DeleteGoogleAdsLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/googleAdsLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_google_ads_link(request, metadata) + pb_request = analytics_admin.DeleteGoogleAdsLinkRequest.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 _DeleteKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteKeyEvent") + + __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: analytics_admin.DeleteKeyEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete key event method over HTTP. + + Args: + request (~.analytics_admin.DeleteKeyEventRequest): + The request object. Request message for DeleteKeyEvent + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/keyEvents/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_key_event(request, metadata) + pb_request = analytics_admin.DeleteKeyEventRequest.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 _DeleteMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteMeasurementProtocolSecret") + + __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: analytics_admin.DeleteMeasurementProtocolSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete measurement + protocol secret method over HTTP. + + Args: + request (~.analytics_admin.DeleteMeasurementProtocolSecretRequest): + The request object. Request message for + DeleteMeasurementProtocolSecret RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_measurement_protocol_secret(request, metadata) + pb_request = analytics_admin.DeleteMeasurementProtocolSecretRequest.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 _DeleteProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteProperty") + + __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: analytics_admin.DeletePropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Property: + r"""Call the delete property method over HTTP. + + Args: + request (~.analytics_admin.DeletePropertyRequest): + The request object. Request message for DeleteProperty + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1alpha/{name=properties/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_property(request, metadata) + pb_request = analytics_admin.DeletePropertyRequest.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 = resources.Property() + pb_resp = resources.Property.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_property(resp) + return resp + + class _DeleteRollupPropertySourceLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteRollupPropertySourceLink") + + __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: analytics_admin.DeleteRollupPropertySourceLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete rollup property + source link method over HTTP. + + Args: + request (~.analytics_admin.DeleteRollupPropertySourceLinkRequest): + The request object. Request message for + DeleteRollupPropertySourceLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/rollupPropertySourceLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_rollup_property_source_link(request, metadata) + pb_request = analytics_admin.DeleteRollupPropertySourceLinkRequest.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 _DeleteSearchAds360Link(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteSearchAds360Link") + + __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: analytics_admin.DeleteSearchAds360LinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete search ads360 link method over HTTP. + + Args: + request (~.analytics_admin.DeleteSearchAds360LinkRequest): + The request object. Request message for + DeleteSearchAds360Link RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/searchAds360Links/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_search_ads360_link(request, metadata) + pb_request = analytics_admin.DeleteSearchAds360LinkRequest.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 _DeleteSKAdNetworkConversionValueSchema(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteSKAdNetworkConversionValueSchema") + + __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: analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete sk ad network + conversion value schema method over HTTP. + + Args: + request (~.analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest): + The request object. Request message for + DeleteSKAdNetworkConversionValueSchema + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_sk_ad_network_conversion_value_schema(request, metadata) + pb_request = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest.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 _DeleteSubpropertyEventFilter(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteSubpropertyEventFilter") + + __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: analytics_admin.DeleteSubpropertyEventFilterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete subproperty event + filter method over HTTP. + + Args: + request (~.analytics_admin.DeleteSubpropertyEventFilterRequest): + The request object. Request message for + DeleteSubpropertyEventFilter RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1alpha/{name=properties/*/subpropertyEventFilters/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_subproperty_event_filter(request, metadata) + pb_request = analytics_admin.DeleteSubpropertyEventFilterRequest.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 _FetchAutomatedGa4ConfigurationOptOut(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("FetchAutomatedGa4ConfigurationOptOut") + + __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: analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse: + r"""Call the fetch automated ga4 + configuration opt out method over HTTP. + + Args: + request (~.analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest): + The request object. Request for fetching the opt out + status for the automated GA4 setup + process. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse: + Response message for fetching the opt + out status for the automated GA4 setup + process. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/properties:fetchAutomatedGa4ConfigurationOptOut', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_fetch_automated_ga4_configuration_opt_out(request, metadata) + pb_request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest.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 = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse() + pb_resp = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_fetch_automated_ga4_configuration_opt_out(resp) + return resp + + class _FetchConnectedGa4Property(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("FetchConnectedGa4Property") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "property" : "", } + + @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: analytics_admin.FetchConnectedGa4PropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.FetchConnectedGa4PropertyResponse: + r"""Call the fetch connected ga4 + property method over HTTP. + + Args: + request (~.analytics_admin.FetchConnectedGa4PropertyRequest): + The request object. Request for looking up GA4 property + connected to a UA property. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.FetchConnectedGa4PropertyResponse: + Response for looking up GA4 property + connected to a UA property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/properties:fetchConnectedGa4Property', + }, + ] + request, metadata = self._interceptor.pre_fetch_connected_ga4_property(request, metadata) + pb_request = analytics_admin.FetchConnectedGa4PropertyRequest.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 = analytics_admin.FetchConnectedGa4PropertyResponse() + pb_resp = analytics_admin.FetchConnectedGa4PropertyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_fetch_connected_ga4_property(resp) + return resp + + class _GetAccessBinding(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetAccessBinding") + + __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: analytics_admin.GetAccessBindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.AccessBinding: + r"""Call the get access binding method over HTTP. + + Args: + request (~.analytics_admin.GetAccessBindingRequest): + The request object. Request message for GetAccessBinding + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.AccessBinding: + A binding of a user to a set of + roles. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=accounts/*/accessBindings/*}', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/accessBindings/*}', + }, + ] + request, metadata = self._interceptor.pre_get_access_binding(request, metadata) + pb_request = analytics_admin.GetAccessBindingRequest.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 = resources.AccessBinding() + pb_resp = resources.AccessBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_access_binding(resp) + return resp + + class _GetAccount(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetAccount") + + __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: analytics_admin.GetAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Account: + r"""Call the get account method over HTTP. + + Args: + request (~.analytics_admin.GetAccountRequest): + The request object. Request message for GetAccount RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Account: + A resource message representing a + Google Analytics account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=accounts/*}', + }, + ] + request, metadata = self._interceptor.pre_get_account(request, metadata) + pb_request = analytics_admin.GetAccountRequest.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 = resources.Account() + pb_resp = resources.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_account(resp) + return resp + + class _GetAdSenseLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetAdSenseLink") + + __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: analytics_admin.GetAdSenseLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.AdSenseLink: + r"""Call the get ad sense link method over HTTP. + + Args: + request (~.analytics_admin.GetAdSenseLinkRequest): + The request object. Request message to be passed to + GetAdSenseLink method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.AdSenseLink: + A link between a GA4 Property and an + AdSense for Content ad client. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/adSenseLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_get_ad_sense_link(request, metadata) + pb_request = analytics_admin.GetAdSenseLinkRequest.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 = resources.AdSenseLink() + pb_resp = resources.AdSenseLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_ad_sense_link(resp) + return resp + + class _GetAttributionSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetAttributionSettings") + + __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: analytics_admin.GetAttributionSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.AttributionSettings: + r"""Call the get attribution settings method over HTTP. + + Args: + request (~.analytics_admin.GetAttributionSettingsRequest): + The request object. Request message for + GetAttributionSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/attributionSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_attribution_settings(request, metadata) + pb_request = analytics_admin.GetAttributionSettingsRequest.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 = resources.AttributionSettings() + pb_resp = resources.AttributionSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_attribution_settings(resp) + return resp + + class _GetAudience(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetAudience") + + __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: analytics_admin.GetAudienceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> audience.Audience: + r"""Call the get audience method over HTTP. + + Args: + request (~.analytics_admin.GetAudienceRequest): + The request object. Request message for GetAudience RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.audience.Audience: + A resource message representing a GA4 + Audience. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/audiences/*}', + }, + ] + request, metadata = self._interceptor.pre_get_audience(request, metadata) + pb_request = analytics_admin.GetAudienceRequest.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 = audience.Audience() + pb_resp = audience.Audience.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_audience(resp) + return resp + + class _GetBigQueryLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetBigQueryLink") + + __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: analytics_admin.GetBigQueryLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.BigQueryLink: + r"""Call the get big query link method over HTTP. + + Args: + request (~.analytics_admin.GetBigQueryLinkRequest): + The request object. Request message for GetBigQueryLink + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/bigQueryLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_get_big_query_link(request, metadata) + pb_request = analytics_admin.GetBigQueryLinkRequest.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 = resources.BigQueryLink() + pb_resp = resources.BigQueryLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_big_query_link(resp) + return resp + + class _GetCalculatedMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetCalculatedMetric") + + __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: analytics_admin.GetCalculatedMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CalculatedMetric: + r"""Call the get calculated metric method over HTTP. + + Args: + request (~.analytics_admin.GetCalculatedMetricRequest): + The request object. Request message for + GetCalculatedMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CalculatedMetric: + A definition for a calculated metric. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/calculatedMetrics/*}', + }, + ] + request, metadata = self._interceptor.pre_get_calculated_metric(request, metadata) + pb_request = analytics_admin.GetCalculatedMetricRequest.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 = resources.CalculatedMetric() + pb_resp = resources.CalculatedMetric.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_calculated_metric(resp) + return resp + + class _GetChannelGroup(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetChannelGroup") + + __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: analytics_admin.GetChannelGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> channel_group.ChannelGroup: + r"""Call the get channel group method over HTTP. + + Args: + request (~.analytics_admin.GetChannelGroupRequest): + The request object. Request message for GetChannelGroup + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.channel_group.ChannelGroup: + A resource message representing a + Channel Group. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/channelGroups/*}', + }, + ] + request, metadata = self._interceptor.pre_get_channel_group(request, metadata) + pb_request = analytics_admin.GetChannelGroupRequest.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 = channel_group.ChannelGroup() + pb_resp = channel_group.ChannelGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_channel_group(resp) + return resp + + class _GetConversionEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetConversionEvent") + + __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: analytics_admin.GetConversionEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ConversionEvent: + r"""Call the get conversion event method over HTTP. + + Args: + request (~.analytics_admin.GetConversionEventRequest): + The request object. Request message for + GetConversionEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/conversionEvents/*}', + }, + ] + request, metadata = self._interceptor.pre_get_conversion_event(request, metadata) + pb_request = analytics_admin.GetConversionEventRequest.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 = resources.ConversionEvent() + pb_resp = resources.ConversionEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_conversion_event(resp) + return resp + + class _GetCustomDimension(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetCustomDimension") + + __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: analytics_admin.GetCustomDimensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomDimension: + r"""Call the get custom dimension method over HTTP. + + Args: + request (~.analytics_admin.GetCustomDimensionRequest): + The request object. Request message for + GetCustomDimension RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomDimension: + A definition for a CustomDimension. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/customDimensions/*}', + }, + ] + request, metadata = self._interceptor.pre_get_custom_dimension(request, metadata) + pb_request = analytics_admin.GetCustomDimensionRequest.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 = resources.CustomDimension() + pb_resp = resources.CustomDimension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_custom_dimension(resp) + return resp + + class _GetCustomMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetCustomMetric") + + __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: analytics_admin.GetCustomMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomMetric: + r"""Call the get custom metric method over HTTP. + + Args: + request (~.analytics_admin.GetCustomMetricRequest): + The request object. Request message for GetCustomMetric + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomMetric: + A definition for a custom metric. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/customMetrics/*}', + }, + ] + request, metadata = self._interceptor.pre_get_custom_metric(request, metadata) + pb_request = analytics_admin.GetCustomMetricRequest.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 = resources.CustomMetric() + pb_resp = resources.CustomMetric.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_custom_metric(resp) + return resp + + class _GetDataRedactionSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetDataRedactionSettings") + + __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: analytics_admin.GetDataRedactionSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataRedactionSettings: + r"""Call the get data redaction + settings method over HTTP. + + Args: + request (~.analytics_admin.GetDataRedactionSettingsRequest): + The request object. Request message for + GetDataRedactionSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataRedactionSettings: + Settings for client-side data + redaction. Singleton resource under a + Web Stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/dataStreams/*/dataRedactionSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_data_redaction_settings(request, metadata) + pb_request = analytics_admin.GetDataRedactionSettingsRequest.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 = resources.DataRedactionSettings() + pb_resp = resources.DataRedactionSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_redaction_settings(resp) + return resp + + class _GetDataRetentionSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetDataRetentionSettings") + + __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: analytics_admin.GetDataRetentionSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataRetentionSettings: + r"""Call the get data retention + settings method over HTTP. + + Args: + request (~.analytics_admin.GetDataRetentionSettingsRequest): + The request object. Request message for + GetDataRetentionSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/dataRetentionSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_data_retention_settings(request, metadata) + pb_request = analytics_admin.GetDataRetentionSettingsRequest.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 = resources.DataRetentionSettings() + pb_resp = resources.DataRetentionSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_retention_settings(resp) + return resp + + class _GetDataSharingSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetDataSharingSettings") + + __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: analytics_admin.GetDataSharingSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataSharingSettings: + r"""Call the get data sharing settings method over HTTP. + + Args: + request (~.analytics_admin.GetDataSharingSettingsRequest): + The request object. Request message for + GetDataSharingSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataSharingSettings: + A resource message representing data + sharing settings of a Google Analytics + account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=accounts/*/dataSharingSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_data_sharing_settings(request, metadata) + pb_request = analytics_admin.GetDataSharingSettingsRequest.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 = resources.DataSharingSettings() + pb_resp = resources.DataSharingSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_sharing_settings(resp) + return resp + + class _GetDataStream(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetDataStream") + + __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: analytics_admin.GetDataStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataStream: + r"""Call the get data stream method over HTTP. + + Args: + request (~.analytics_admin.GetDataStreamRequest): + The request object. Request message for GetDataStream + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataStream: + A resource message representing a + data stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/dataStreams/*}', + }, + ] + request, metadata = self._interceptor.pre_get_data_stream(request, metadata) + pb_request = analytics_admin.GetDataStreamRequest.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 = resources.DataStream() + pb_resp = resources.DataStream.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_stream(resp) + return resp + + class _GetDisplayVideo360AdvertiserLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetDisplayVideo360AdvertiserLink") + + __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: analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Call the get display video360 + advertiser link method over HTTP. + + Args: + request (~.analytics_admin.GetDisplayVideo360AdvertiserLinkRequest): + The request object. Request message for + GetDisplayVideo360AdvertiserLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/displayVideo360AdvertiserLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_get_display_video360_advertiser_link(request, metadata) + pb_request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest.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 = resources.DisplayVideo360AdvertiserLink() + pb_resp = resources.DisplayVideo360AdvertiserLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_display_video360_advertiser_link(resp) + return resp + + class _GetDisplayVideo360AdvertiserLinkProposal(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetDisplayVideo360AdvertiserLinkProposal") + + __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: analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DisplayVideo360AdvertiserLinkProposal: + r"""Call the get display video360 + advertiser link proposal method over HTTP. + + Args: + request (~.analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest): + The request object. Request message for + GetDisplayVideo360AdvertiserLinkProposal + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DisplayVideo360AdvertiserLinkProposal: + A proposal for a link between a GA4 + property and a Display & Video 360 + advertiser. + + A proposal is converted to a + DisplayVideo360AdvertiserLink once + approved. Google Analytics admins + approve inbound proposals while Display + & Video 360 admins approve outbound + proposals. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}', + }, + ] + request, metadata = self._interceptor.pre_get_display_video360_advertiser_link_proposal(request, metadata) + pb_request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest.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 = resources.DisplayVideo360AdvertiserLinkProposal() + pb_resp = resources.DisplayVideo360AdvertiserLinkProposal.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_display_video360_advertiser_link_proposal(resp) + return resp + + class _GetEnhancedMeasurementSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetEnhancedMeasurementSettings") + + __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: analytics_admin.GetEnhancedMeasurementSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.EnhancedMeasurementSettings: + r"""Call the get enhanced measurement + settings method over HTTP. + + Args: + request (~.analytics_admin.GetEnhancedMeasurementSettingsRequest): + The request object. Request message for + GetEnhancedMeasurementSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/dataStreams/*/enhancedMeasurementSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_enhanced_measurement_settings(request, metadata) + pb_request = analytics_admin.GetEnhancedMeasurementSettingsRequest.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 = resources.EnhancedMeasurementSettings() + pb_resp = resources.EnhancedMeasurementSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_enhanced_measurement_settings(resp) + return resp + + class _GetEventCreateRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetEventCreateRule") + + __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: analytics_admin.GetEventCreateRuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> event_create_and_edit.EventCreateRule: + r"""Call the get event create rule method over HTTP. + + Args: + request (~.analytics_admin.GetEventCreateRuleRequest): + The request object. Request message for + GetEventCreateRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_create_and_edit.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/dataStreams/*/eventCreateRules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_event_create_rule(request, metadata) + pb_request = analytics_admin.GetEventCreateRuleRequest.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 = event_create_and_edit.EventCreateRule() + pb_resp = event_create_and_edit.EventCreateRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_event_create_rule(resp) + return resp + + class _GetEventEditRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetEventEditRule") + + __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: analytics_admin.GetEventEditRuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> event_create_and_edit.EventEditRule: + r"""Call the get event edit rule method over HTTP. + + Args: + request (~.analytics_admin.GetEventEditRuleRequest): + The request object. Request message for GetEventEditRule + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_create_and_edit.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/dataStreams/*/eventEditRules/*}', + }, + ] + request, metadata = self._interceptor.pre_get_event_edit_rule(request, metadata) + pb_request = analytics_admin.GetEventEditRuleRequest.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 = event_create_and_edit.EventEditRule() + pb_resp = event_create_and_edit.EventEditRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_event_edit_rule(resp) + return resp + + class _GetExpandedDataSet(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetExpandedDataSet") + + __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: analytics_admin.GetExpandedDataSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> expanded_data_set.ExpandedDataSet: + r"""Call the get expanded data set method over HTTP. + + Args: + request (~.analytics_admin.GetExpandedDataSetRequest): + The request object. Request message for + GetExpandedDataSet RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.expanded_data_set.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/expandedDataSets/*}', + }, + ] + request, metadata = self._interceptor.pre_get_expanded_data_set(request, metadata) + pb_request = analytics_admin.GetExpandedDataSetRequest.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 = expanded_data_set.ExpandedDataSet() + pb_resp = expanded_data_set.ExpandedDataSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_expanded_data_set(resp) + return resp + + class _GetGlobalSiteTag(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetGlobalSiteTag") + + __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: analytics_admin.GetGlobalSiteTagRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.GlobalSiteTag: + r"""Call the get global site tag method over HTTP. + + Args: + request (~.analytics_admin.GetGlobalSiteTagRequest): + The request object. Request message for GetGlobalSiteTag + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.GlobalSiteTag: + Read-only resource with the tag for + sending data from a website to a + DataStream. Only present for web + DataStream resources. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/dataStreams/*/globalSiteTag}', + }, + ] + request, metadata = self._interceptor.pre_get_global_site_tag(request, metadata) + pb_request = analytics_admin.GetGlobalSiteTagRequest.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 = resources.GlobalSiteTag() + pb_resp = resources.GlobalSiteTag.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_global_site_tag(resp) + return resp + + class _GetGoogleSignalsSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetGoogleSignalsSettings") + + __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: analytics_admin.GetGoogleSignalsSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.GoogleSignalsSettings: + r"""Call the get google signals + settings method over HTTP. + + Args: + request (~.analytics_admin.GetGoogleSignalsSettingsRequest): + The request object. Request message for + GetGoogleSignalsSettings RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.GoogleSignalsSettings: + Settings values for Google Signals. + This is a singleton resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/googleSignalsSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_google_signals_settings(request, metadata) + pb_request = analytics_admin.GetGoogleSignalsSettingsRequest.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 = resources.GoogleSignalsSettings() + pb_resp = resources.GoogleSignalsSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_google_signals_settings(resp) + return resp + + class _GetKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetKeyEvent") + + __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: analytics_admin.GetKeyEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.KeyEvent: + r"""Call the get key event method over HTTP. + + Args: + request (~.analytics_admin.GetKeyEventRequest): + The request object. Request message for GetKeyEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.KeyEvent: + A key event in a Google Analytics + property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/keyEvents/*}', + }, + ] + request, metadata = self._interceptor.pre_get_key_event(request, metadata) + pb_request = analytics_admin.GetKeyEventRequest.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 = resources.KeyEvent() + pb_resp = resources.KeyEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_key_event(resp) + return resp + + class _GetMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetMeasurementProtocolSecret") + + __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: analytics_admin.GetMeasurementProtocolSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.MeasurementProtocolSecret: + r"""Call the get measurement protocol + secret method over HTTP. + + Args: + request (~.analytics_admin.GetMeasurementProtocolSecretRequest): + The request object. Request message for + GetMeasurementProtocolSecret RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}', + }, + ] + request, metadata = self._interceptor.pre_get_measurement_protocol_secret(request, metadata) + pb_request = analytics_admin.GetMeasurementProtocolSecretRequest.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 = resources.MeasurementProtocolSecret() + pb_resp = resources.MeasurementProtocolSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_measurement_protocol_secret(resp) + return resp + + class _GetProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetProperty") + + __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: analytics_admin.GetPropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Property: + r"""Call the get property method over HTTP. + + Args: + request (~.analytics_admin.GetPropertyRequest): + The request object. Request message for GetProperty RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*}', + }, + ] + request, metadata = self._interceptor.pre_get_property(request, metadata) + pb_request = analytics_admin.GetPropertyRequest.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 = resources.Property() + pb_resp = resources.Property.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_property(resp) + return resp + + class _GetRollupPropertySourceLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetRollupPropertySourceLink") + + __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: analytics_admin.GetRollupPropertySourceLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.RollupPropertySourceLink: + r"""Call the get rollup property + source link method over HTTP. + + Args: + request (~.analytics_admin.GetRollupPropertySourceLinkRequest): + The request object. Request message for + GetRollupPropertySourceLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.RollupPropertySourceLink: + A link that references a source + property under the parent rollup + property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/rollupPropertySourceLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_get_rollup_property_source_link(request, metadata) + pb_request = analytics_admin.GetRollupPropertySourceLinkRequest.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 = resources.RollupPropertySourceLink() + pb_resp = resources.RollupPropertySourceLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_rollup_property_source_link(resp) + return resp + + class _GetSearchAds360Link(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetSearchAds360Link") + + __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: analytics_admin.GetSearchAds360LinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.SearchAds360Link: + r"""Call the get search ads360 link method over HTTP. + + Args: + request (~.analytics_admin.GetSearchAds360LinkRequest): + The request object. Request message for + GetSearchAds360Link RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/searchAds360Links/*}', + }, + ] + request, metadata = self._interceptor.pre_get_search_ads360_link(request, metadata) + pb_request = analytics_admin.GetSearchAds360LinkRequest.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 = resources.SearchAds360Link() + pb_resp = resources.SearchAds360Link.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_search_ads360_link(resp) + return resp + + class _GetSKAdNetworkConversionValueSchema(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetSKAdNetworkConversionValueSchema") + + __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: analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.SKAdNetworkConversionValueSchema: + r"""Call the get sk ad network + conversion value schema method over HTTP. + + Args: + request (~.analytics_admin.GetSKAdNetworkConversionValueSchemaRequest): + The request object. Request message for + GetSKAdNetworkConversionValueSchema RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SKAdNetworkConversionValueSchema: + SKAdNetwork conversion value schema + of an iOS stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}', + }, + ] + request, metadata = self._interceptor.pre_get_sk_ad_network_conversion_value_schema(request, metadata) + pb_request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest.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 = resources.SKAdNetworkConversionValueSchema() + pb_resp = resources.SKAdNetworkConversionValueSchema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_sk_ad_network_conversion_value_schema(resp) + return resp + + class _GetSubpropertyEventFilter(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetSubpropertyEventFilter") + + __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: analytics_admin.GetSubpropertyEventFilterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> subproperty_event_filter.SubpropertyEventFilter: + r"""Call the get subproperty event + filter method over HTTP. + + Args: + request (~.analytics_admin.GetSubpropertyEventFilterRequest): + The request object. Request message for + GetSubpropertyEventFilter RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.subproperty_event_filter.SubpropertyEventFilter: + A resource message representing a GA4 + Subproperty event filter. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{name=properties/*/subpropertyEventFilters/*}', + }, + ] + request, metadata = self._interceptor.pre_get_subproperty_event_filter(request, metadata) + pb_request = analytics_admin.GetSubpropertyEventFilterRequest.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 = subproperty_event_filter.SubpropertyEventFilter() + pb_resp = subproperty_event_filter.SubpropertyEventFilter.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_subproperty_event_filter(resp) + return resp + + class _ListAccessBindings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListAccessBindings") + + __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: analytics_admin.ListAccessBindingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListAccessBindingsResponse: + r"""Call the list access bindings method over HTTP. + + Args: + request (~.analytics_admin.ListAccessBindingsRequest): + The request object. Request message for + ListAccessBindings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListAccessBindingsResponse: + Response message for + ListAccessBindings RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=accounts/*}/accessBindings', + }, +{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/accessBindings', + }, + ] + request, metadata = self._interceptor.pre_list_access_bindings(request, metadata) + pb_request = analytics_admin.ListAccessBindingsRequest.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 = analytics_admin.ListAccessBindingsResponse() + pb_resp = analytics_admin.ListAccessBindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_access_bindings(resp) + return resp + + class _ListAccounts(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListAccounts") + + def __call__(self, + request: analytics_admin.ListAccountsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListAccountsResponse: + r"""Call the list accounts method over HTTP. + + Args: + request (~.analytics_admin.ListAccountsRequest): + The request object. Request message for ListAccounts RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListAccountsResponse: + Request message for ListAccounts RPC. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/accounts', + }, + ] + request, metadata = self._interceptor.pre_list_accounts(request, metadata) + pb_request = analytics_admin.ListAccountsRequest.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 = analytics_admin.ListAccountsResponse() + pb_resp = analytics_admin.ListAccountsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_accounts(resp) + return resp + + class _ListAccountSummaries(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListAccountSummaries") + + def __call__(self, + request: analytics_admin.ListAccountSummariesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListAccountSummariesResponse: + r"""Call the list account summaries method over HTTP. + + Args: + request (~.analytics_admin.ListAccountSummariesRequest): + The request object. Request message for + ListAccountSummaries RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListAccountSummariesResponse: + Response message for + ListAccountSummaries RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/accountSummaries', + }, + ] + request, metadata = self._interceptor.pre_list_account_summaries(request, metadata) + pb_request = analytics_admin.ListAccountSummariesRequest.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 = analytics_admin.ListAccountSummariesResponse() + pb_resp = analytics_admin.ListAccountSummariesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_account_summaries(resp) + return resp + + class _ListAdSenseLinks(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListAdSenseLinks") + + __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: analytics_admin.ListAdSenseLinksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListAdSenseLinksResponse: + r"""Call the list ad sense links method over HTTP. + + Args: + request (~.analytics_admin.ListAdSenseLinksRequest): + The request object. Request message to be passed to + ListAdSenseLinks method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListAdSenseLinksResponse: + Response message for ListAdSenseLinks + method. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/adSenseLinks', + }, + ] + request, metadata = self._interceptor.pre_list_ad_sense_links(request, metadata) + pb_request = analytics_admin.ListAdSenseLinksRequest.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 = analytics_admin.ListAdSenseLinksResponse() + pb_resp = analytics_admin.ListAdSenseLinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_ad_sense_links(resp) + return resp + + class _ListAudiences(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListAudiences") + + __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: analytics_admin.ListAudiencesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListAudiencesResponse: + r"""Call the list audiences method over HTTP. + + Args: + request (~.analytics_admin.ListAudiencesRequest): + The request object. Request message for ListAudiences + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListAudiencesResponse: + Response message for ListAudiences + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/audiences', + }, + ] + request, metadata = self._interceptor.pre_list_audiences(request, metadata) + pb_request = analytics_admin.ListAudiencesRequest.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 = analytics_admin.ListAudiencesResponse() + pb_resp = analytics_admin.ListAudiencesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_audiences(resp) + return resp + + class _ListBigQueryLinks(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListBigQueryLinks") + + __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: analytics_admin.ListBigQueryLinksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListBigQueryLinksResponse: + r"""Call the list big query links method over HTTP. + + Args: + request (~.analytics_admin.ListBigQueryLinksRequest): + The request object. Request message for ListBigQueryLinks + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListBigQueryLinksResponse: + Response message for + ListBigQueryLinks RPC + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/bigQueryLinks', + }, + ] + request, metadata = self._interceptor.pre_list_big_query_links(request, metadata) + pb_request = analytics_admin.ListBigQueryLinksRequest.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 = analytics_admin.ListBigQueryLinksResponse() + pb_resp = analytics_admin.ListBigQueryLinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_big_query_links(resp) + return resp + + class _ListCalculatedMetrics(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListCalculatedMetrics") + + __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: analytics_admin.ListCalculatedMetricsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListCalculatedMetricsResponse: + r"""Call the list calculated metrics method over HTTP. + + Args: + request (~.analytics_admin.ListCalculatedMetricsRequest): + The request object. Request message for + ListCalculatedMetrics RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListCalculatedMetricsResponse: + Response message for + ListCalculatedMetrics RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/calculatedMetrics', + }, + ] + request, metadata = self._interceptor.pre_list_calculated_metrics(request, metadata) + pb_request = analytics_admin.ListCalculatedMetricsRequest.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 = analytics_admin.ListCalculatedMetricsResponse() + pb_resp = analytics_admin.ListCalculatedMetricsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_calculated_metrics(resp) + return resp + + class _ListChannelGroups(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListChannelGroups") + + __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: analytics_admin.ListChannelGroupsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListChannelGroupsResponse: + r"""Call the list channel groups method over HTTP. + + Args: + request (~.analytics_admin.ListChannelGroupsRequest): + The request object. Request message for ListChannelGroups + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListChannelGroupsResponse: + Response message for + ListChannelGroups RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/channelGroups', + }, + ] + request, metadata = self._interceptor.pre_list_channel_groups(request, metadata) + pb_request = analytics_admin.ListChannelGroupsRequest.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 = analytics_admin.ListChannelGroupsResponse() + pb_resp = analytics_admin.ListChannelGroupsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_channel_groups(resp) + return resp + + class _ListConnectedSiteTags(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListConnectedSiteTags") + + def __call__(self, + request: analytics_admin.ListConnectedSiteTagsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListConnectedSiteTagsResponse: + r"""Call the list connected site tags method over HTTP. + + Args: + request (~.analytics_admin.ListConnectedSiteTagsRequest): + The request object. Request message for + ListConnectedSiteTags RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListConnectedSiteTagsResponse: + Response message for + ListConnectedSiteTags RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/properties:listConnectedSiteTags', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_list_connected_site_tags(request, metadata) + pb_request = analytics_admin.ListConnectedSiteTagsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_admin.ListConnectedSiteTagsResponse() + pb_resp = analytics_admin.ListConnectedSiteTagsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_connected_site_tags(resp) + return resp + + class _ListConversionEvents(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListConversionEvents") + + __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: analytics_admin.ListConversionEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListConversionEventsResponse: + r"""Call the list conversion events method over HTTP. + + Args: + request (~.analytics_admin.ListConversionEventsRequest): + The request object. Request message for + ListConversionEvents RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListConversionEventsResponse: + Response message for + ListConversionEvents RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/conversionEvents', + }, + ] + request, metadata = self._interceptor.pre_list_conversion_events(request, metadata) + pb_request = analytics_admin.ListConversionEventsRequest.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 = analytics_admin.ListConversionEventsResponse() + pb_resp = analytics_admin.ListConversionEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_conversion_events(resp) + return resp + + class _ListCustomDimensions(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListCustomDimensions") + + __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: analytics_admin.ListCustomDimensionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListCustomDimensionsResponse: + r"""Call the list custom dimensions method over HTTP. + + Args: + request (~.analytics_admin.ListCustomDimensionsRequest): + The request object. Request message for + ListCustomDimensions RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListCustomDimensionsResponse: + Response message for + ListCustomDimensions RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/customDimensions', + }, + ] + request, metadata = self._interceptor.pre_list_custom_dimensions(request, metadata) + pb_request = analytics_admin.ListCustomDimensionsRequest.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 = analytics_admin.ListCustomDimensionsResponse() + pb_resp = analytics_admin.ListCustomDimensionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_custom_dimensions(resp) + return resp + + class _ListCustomMetrics(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListCustomMetrics") + + __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: analytics_admin.ListCustomMetricsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListCustomMetricsResponse: + r"""Call the list custom metrics method over HTTP. + + Args: + request (~.analytics_admin.ListCustomMetricsRequest): + The request object. Request message for ListCustomMetrics + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListCustomMetricsResponse: + Response message for + ListCustomMetrics RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/customMetrics', + }, + ] + request, metadata = self._interceptor.pre_list_custom_metrics(request, metadata) + pb_request = analytics_admin.ListCustomMetricsRequest.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 = analytics_admin.ListCustomMetricsResponse() + pb_resp = analytics_admin.ListCustomMetricsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_custom_metrics(resp) + return resp + + class _ListDataStreams(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListDataStreams") + + __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: analytics_admin.ListDataStreamsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListDataStreamsResponse: + r"""Call the list data streams method over HTTP. + + Args: + request (~.analytics_admin.ListDataStreamsRequest): + The request object. Request message for ListDataStreams + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListDataStreamsResponse: + Response message for ListDataStreams + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/dataStreams', + }, + ] + request, metadata = self._interceptor.pre_list_data_streams(request, metadata) + pb_request = analytics_admin.ListDataStreamsRequest.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 = analytics_admin.ListDataStreamsResponse() + pb_resp = analytics_admin.ListDataStreamsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_data_streams(resp) + return resp + + class _ListDisplayVideo360AdvertiserLinkProposals(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListDisplayVideo360AdvertiserLinkProposals") + + __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: analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse: + r"""Call the list display video360 + advertiser link proposals method over HTTP. + + Args: + request (~.analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest): + The request object. Request message for + ListDisplayVideo360AdvertiserLinkProposals + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse: + Response message for + ListDisplayVideo360AdvertiserLinkProposals + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinkProposals', + }, + ] + request, metadata = self._interceptor.pre_list_display_video360_advertiser_link_proposals(request, metadata) + pb_request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest.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 = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + pb_resp = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_display_video360_advertiser_link_proposals(resp) + return resp + + class _ListDisplayVideo360AdvertiserLinks(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListDisplayVideo360AdvertiserLinks") + + __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: analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListDisplayVideo360AdvertiserLinksResponse: + r"""Call the list display video360 + advertiser links method over HTTP. + + Args: + request (~.analytics_admin.ListDisplayVideo360AdvertiserLinksRequest): + The request object. Request message for + ListDisplayVideo360AdvertiserLinks RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListDisplayVideo360AdvertiserLinksResponse: + Response message for + ListDisplayVideo360AdvertiserLinks RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinks', + }, + ] + request, metadata = self._interceptor.pre_list_display_video360_advertiser_links(request, metadata) + pb_request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest.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 = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + pb_resp = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_display_video360_advertiser_links(resp) + return resp + + class _ListEventCreateRules(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListEventCreateRules") + + __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: analytics_admin.ListEventCreateRulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListEventCreateRulesResponse: + r"""Call the list event create rules method over HTTP. + + Args: + request (~.analytics_admin.ListEventCreateRulesRequest): + The request object. Request message for + ListEventCreateRules RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListEventCreateRulesResponse: + Response message for + ListEventCreateRules RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*/dataStreams/*}/eventCreateRules', + }, + ] + request, metadata = self._interceptor.pre_list_event_create_rules(request, metadata) + pb_request = analytics_admin.ListEventCreateRulesRequest.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 = analytics_admin.ListEventCreateRulesResponse() + pb_resp = analytics_admin.ListEventCreateRulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_event_create_rules(resp) + return resp + + class _ListEventEditRules(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListEventEditRules") + + __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: analytics_admin.ListEventEditRulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListEventEditRulesResponse: + r"""Call the list event edit rules method over HTTP. + + Args: + request (~.analytics_admin.ListEventEditRulesRequest): + The request object. Request message for + ListEventEditRules RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListEventEditRulesResponse: + Response message for + ListEventEditRules RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules', + }, + ] + request, metadata = self._interceptor.pre_list_event_edit_rules(request, metadata) + pb_request = analytics_admin.ListEventEditRulesRequest.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 = analytics_admin.ListEventEditRulesResponse() + pb_resp = analytics_admin.ListEventEditRulesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_event_edit_rules(resp) + return resp + + class _ListExpandedDataSets(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListExpandedDataSets") + + __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: analytics_admin.ListExpandedDataSetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListExpandedDataSetsResponse: + r"""Call the list expanded data sets method over HTTP. + + Args: + request (~.analytics_admin.ListExpandedDataSetsRequest): + The request object. Request message for + ListExpandedDataSets RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListExpandedDataSetsResponse: + Response message for + ListExpandedDataSets RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/expandedDataSets', + }, + ] + request, metadata = self._interceptor.pre_list_expanded_data_sets(request, metadata) + pb_request = analytics_admin.ListExpandedDataSetsRequest.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 = analytics_admin.ListExpandedDataSetsResponse() + pb_resp = analytics_admin.ListExpandedDataSetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_expanded_data_sets(resp) + return resp + + class _ListFirebaseLinks(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListFirebaseLinks") + + __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: analytics_admin.ListFirebaseLinksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListFirebaseLinksResponse: + r"""Call the list firebase links method over HTTP. + + Args: + request (~.analytics_admin.ListFirebaseLinksRequest): + The request object. Request message for ListFirebaseLinks + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListFirebaseLinksResponse: + Response message for + ListFirebaseLinks RPC + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/firebaseLinks', + }, + ] + request, metadata = self._interceptor.pre_list_firebase_links(request, metadata) + pb_request = analytics_admin.ListFirebaseLinksRequest.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 = analytics_admin.ListFirebaseLinksResponse() + pb_resp = analytics_admin.ListFirebaseLinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_firebase_links(resp) + return resp + + class _ListGoogleAdsLinks(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListGoogleAdsLinks") + + __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: analytics_admin.ListGoogleAdsLinksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListGoogleAdsLinksResponse: + r"""Call the list google ads links method over HTTP. + + Args: + request (~.analytics_admin.ListGoogleAdsLinksRequest): + The request object. Request message for + ListGoogleAdsLinks RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListGoogleAdsLinksResponse: + Response message for + ListGoogleAdsLinks RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/googleAdsLinks', + }, + ] + request, metadata = self._interceptor.pre_list_google_ads_links(request, metadata) + pb_request = analytics_admin.ListGoogleAdsLinksRequest.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 = analytics_admin.ListGoogleAdsLinksResponse() + pb_resp = analytics_admin.ListGoogleAdsLinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_google_ads_links(resp) + return resp + + class _ListKeyEvents(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListKeyEvents") + + __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: analytics_admin.ListKeyEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListKeyEventsResponse: + r"""Call the list key events method over HTTP. + + Args: + request (~.analytics_admin.ListKeyEventsRequest): + The request object. Request message for ListKeyEvents RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListKeyEventsResponse: + Response message for ListKeyEvents + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/keyEvents', + }, + ] + request, metadata = self._interceptor.pre_list_key_events(request, metadata) + pb_request = analytics_admin.ListKeyEventsRequest.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 = analytics_admin.ListKeyEventsResponse() + pb_resp = analytics_admin.ListKeyEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_key_events(resp) + return resp + + class _ListMeasurementProtocolSecrets(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListMeasurementProtocolSecrets") + + __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: analytics_admin.ListMeasurementProtocolSecretsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListMeasurementProtocolSecretsResponse: + r"""Call the list measurement protocol + secrets method over HTTP. + + Args: + request (~.analytics_admin.ListMeasurementProtocolSecretsRequest): + The request object. Request message for + ListMeasurementProtocolSecret RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListMeasurementProtocolSecretsResponse: + Response message for + ListMeasurementProtocolSecret RPC + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets', + }, + ] + request, metadata = self._interceptor.pre_list_measurement_protocol_secrets(request, metadata) + pb_request = analytics_admin.ListMeasurementProtocolSecretsRequest.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 = analytics_admin.ListMeasurementProtocolSecretsResponse() + pb_resp = analytics_admin.ListMeasurementProtocolSecretsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_measurement_protocol_secrets(resp) + return resp + + class _ListProperties(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListProperties") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "filter" : "", } + + @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: analytics_admin.ListPropertiesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListPropertiesResponse: + r"""Call the list properties method over HTTP. + + Args: + request (~.analytics_admin.ListPropertiesRequest): + The request object. Request message for ListProperties + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListPropertiesResponse: + Response message for ListProperties + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/properties', + }, + ] + request, metadata = self._interceptor.pre_list_properties(request, metadata) + pb_request = analytics_admin.ListPropertiesRequest.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 = analytics_admin.ListPropertiesResponse() + pb_resp = analytics_admin.ListPropertiesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_properties(resp) + return resp + + class _ListRollupPropertySourceLinks(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListRollupPropertySourceLinks") + + __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: analytics_admin.ListRollupPropertySourceLinksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListRollupPropertySourceLinksResponse: + r"""Call the list rollup property + source links method over HTTP. + + Args: + request (~.analytics_admin.ListRollupPropertySourceLinksRequest): + The request object. Request message for + ListRollupPropertySourceLinks RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListRollupPropertySourceLinksResponse: + Response message for + ListRollupPropertySourceLinks RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/rollupPropertySourceLinks', + }, + ] + request, metadata = self._interceptor.pre_list_rollup_property_source_links(request, metadata) + pb_request = analytics_admin.ListRollupPropertySourceLinksRequest.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 = analytics_admin.ListRollupPropertySourceLinksResponse() + pb_resp = analytics_admin.ListRollupPropertySourceLinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_rollup_property_source_links(resp) + return resp + + class _ListSearchAds360Links(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListSearchAds360Links") + + __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: analytics_admin.ListSearchAds360LinksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListSearchAds360LinksResponse: + r"""Call the list search ads360 links method over HTTP. + + Args: + request (~.analytics_admin.ListSearchAds360LinksRequest): + The request object. Request message for + ListSearchAds360Links RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListSearchAds360LinksResponse: + Response message for + ListSearchAds360Links RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/searchAds360Links', + }, + ] + request, metadata = self._interceptor.pre_list_search_ads360_links(request, metadata) + pb_request = analytics_admin.ListSearchAds360LinksRequest.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 = analytics_admin.ListSearchAds360LinksResponse() + pb_resp = analytics_admin.ListSearchAds360LinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_search_ads360_links(resp) + return resp + + class _ListSKAdNetworkConversionValueSchemas(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListSKAdNetworkConversionValueSchemas") + + __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: analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListSKAdNetworkConversionValueSchemasResponse: + r"""Call the list sk ad network + conversion value schemas method over HTTP. + + Args: + request (~.analytics_admin.ListSKAdNetworkConversionValueSchemasRequest): + The request object. Request message for + ListSKAdNetworkConversionValueSchemas + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListSKAdNetworkConversionValueSchemasResponse: + Response message for + ListSKAdNetworkConversionValueSchemas + RPC + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*/dataStreams/*}/sKAdNetworkConversionValueSchema', + }, + ] + request, metadata = self._interceptor.pre_list_sk_ad_network_conversion_value_schemas(request, metadata) + pb_request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest.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 = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + pb_resp = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_sk_ad_network_conversion_value_schemas(resp) + return resp + + class _ListSubpropertyEventFilters(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListSubpropertyEventFilters") + + __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: analytics_admin.ListSubpropertyEventFiltersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListSubpropertyEventFiltersResponse: + r"""Call the list subproperty event + filters method over HTTP. + + Args: + request (~.analytics_admin.ListSubpropertyEventFiltersRequest): + The request object. Request message for + ListSubpropertyEventFilters RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListSubpropertyEventFiltersResponse: + Response message for + ListSubpropertyEventFilter RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1alpha/{parent=properties/*}/subpropertyEventFilters', + }, + ] + request, metadata = self._interceptor.pre_list_subproperty_event_filters(request, metadata) + pb_request = analytics_admin.ListSubpropertyEventFiltersRequest.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 = analytics_admin.ListSubpropertyEventFiltersResponse() + pb_resp = analytics_admin.ListSubpropertyEventFiltersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_subproperty_event_filters(resp) + return resp + + class _ProvisionAccountTicket(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ProvisionAccountTicket") + + def __call__(self, + request: analytics_admin.ProvisionAccountTicketRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ProvisionAccountTicketResponse: + r"""Call the provision account ticket method over HTTP. + + Args: + request (~.analytics_admin.ProvisionAccountTicketRequest): + The request object. Request message for + ProvisionAccountTicket RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ProvisionAccountTicketResponse: + Response message for + ProvisionAccountTicket RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/accounts:provisionAccountTicket', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_provision_account_ticket(request, metadata) + pb_request = analytics_admin.ProvisionAccountTicketRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_admin.ProvisionAccountTicketResponse() + pb_resp = analytics_admin.ProvisionAccountTicketResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_provision_account_ticket(resp) + return resp + + class _ProvisionSubproperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ProvisionSubproperty") + + __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: analytics_admin.ProvisionSubpropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ProvisionSubpropertyResponse: + r"""Call the provision subproperty method over HTTP. + + Args: + request (~.analytics_admin.ProvisionSubpropertyRequest): + The request object. Request message for CreateSubproperty + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ProvisionSubpropertyResponse: + Response message for + ProvisionSubproperty RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/properties:provisionSubproperty', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_provision_subproperty(request, metadata) + pb_request = analytics_admin.ProvisionSubpropertyRequest.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 = analytics_admin.ProvisionSubpropertyResponse() + pb_resp = analytics_admin.ProvisionSubpropertyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_provision_subproperty(resp) + return resp + + class _ReorderEventEditRules(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ReorderEventEditRules") + + __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: analytics_admin.ReorderEventEditRulesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the reorder event edit rules method over HTTP. + + Args: + request (~.analytics_admin.ReorderEventEditRulesRequest): + The request object. Request message for + ReorderEventEditRules RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules:reorder', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_reorder_event_edit_rules(request, metadata) + pb_request = analytics_admin.ReorderEventEditRulesRequest.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) + + class _RunAccessReport(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("RunAccessReport") + + def __call__(self, + request: analytics_admin.RunAccessReportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.RunAccessReportResponse: + r"""Call the run access report method over HTTP. + + Args: + request (~.analytics_admin.RunAccessReportRequest): + The request object. The request for a Data Access Record + Report. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.RunAccessReportResponse: + The customized Data Access Record + Report response. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{entity=properties/*}:runAccessReport', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1alpha/{entity=accounts/*}:runAccessReport', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_access_report(request, metadata) + pb_request = analytics_admin.RunAccessReportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_admin.RunAccessReportResponse() + pb_resp = analytics_admin.RunAccessReportResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_run_access_report(resp) + return resp + + class _SearchChangeHistoryEvents(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("SearchChangeHistoryEvents") + + __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: analytics_admin.SearchChangeHistoryEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.SearchChangeHistoryEventsResponse: + r"""Call the search change history + events method over HTTP. + + Args: + request (~.analytics_admin.SearchChangeHistoryEventsRequest): + The request object. Request message for + SearchChangeHistoryEvents RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.SearchChangeHistoryEventsResponse: + Response message for SearchAccounts + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/{account=accounts/*}:searchChangeHistoryEvents', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_search_change_history_events(request, metadata) + pb_request = analytics_admin.SearchChangeHistoryEventsRequest.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 = analytics_admin.SearchChangeHistoryEventsResponse() + pb_resp = analytics_admin.SearchChangeHistoryEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_change_history_events(resp) + return resp + + class _SetAutomatedGa4ConfigurationOptOut(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("SetAutomatedGa4ConfigurationOptOut") + + __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: analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse: + r"""Call the set automated ga4 + configuration opt out method over HTTP. + + Args: + request (~.analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest): + The request object. Request for setting the opt out + status for the automated GA4 setup + process. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse: + Response message for setting the opt + out status for the automated GA4 setup + process. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1alpha/properties:setAutomatedGa4ConfigurationOptOut', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_set_automated_ga4_configuration_opt_out(request, metadata) + pb_request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest.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 = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + pb_resp = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_automated_ga4_configuration_opt_out(resp) + return resp + + class _UpdateAccessBinding(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateAccessBinding") + + __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: analytics_admin.UpdateAccessBindingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.AccessBinding: + r"""Call the update access binding method over HTTP. + + Args: + request (~.analytics_admin.UpdateAccessBindingRequest): + The request object. Request message for + UpdateAccessBinding RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.AccessBinding: + A binding of a user to a set of + roles. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{access_binding.name=accounts/*/accessBindings/*}', + 'body': 'access_binding', + }, +{ + 'method': 'patch', + 'uri': '/v1alpha/{access_binding.name=properties/*/accessBindings/*}', + 'body': 'access_binding', + }, + ] + request, metadata = self._interceptor.pre_update_access_binding(request, metadata) + pb_request = analytics_admin.UpdateAccessBindingRequest.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 = resources.AccessBinding() + pb_resp = resources.AccessBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_access_binding(resp) + return resp + + class _UpdateAccount(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateAccount") + + __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: analytics_admin.UpdateAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Account: + r"""Call the update account method over HTTP. + + Args: + request (~.analytics_admin.UpdateAccountRequest): + The request object. Request message for UpdateAccount + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Account: + A resource message representing a + Google Analytics account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{account.name=accounts/*}', + 'body': 'account', + }, + ] + request, metadata = self._interceptor.pre_update_account(request, metadata) + pb_request = analytics_admin.UpdateAccountRequest.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 = resources.Account() + pb_resp = resources.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_account(resp) + return resp + + class _UpdateAttributionSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateAttributionSettings") + + __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: analytics_admin.UpdateAttributionSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.AttributionSettings: + r"""Call the update attribution + settings method over HTTP. + + Args: + request (~.analytics_admin.UpdateAttributionSettingsRequest): + The request object. Request message for + UpdateAttributionSettings RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.AttributionSettings: + The attribution settings used for a + given property. This is a singleton + resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{attribution_settings.name=properties/*/attributionSettings}', + 'body': 'attribution_settings', + }, + ] + request, metadata = self._interceptor.pre_update_attribution_settings(request, metadata) + pb_request = analytics_admin.UpdateAttributionSettingsRequest.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 = resources.AttributionSettings() + pb_resp = resources.AttributionSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_attribution_settings(resp) + return resp + + class _UpdateAudience(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateAudience") + + __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: analytics_admin.UpdateAudienceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gaa_audience.Audience: + r"""Call the update audience method over HTTP. + + Args: + request (~.analytics_admin.UpdateAudienceRequest): + The request object. Request message for UpdateAudience + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gaa_audience.Audience: + A resource message representing a GA4 + Audience. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{audience.name=properties/*/audiences/*}', + 'body': 'audience', + }, + ] + request, metadata = self._interceptor.pre_update_audience(request, metadata) + pb_request = analytics_admin.UpdateAudienceRequest.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 = gaa_audience.Audience() + pb_resp = gaa_audience.Audience.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_audience(resp) + return resp + + class _UpdateBigQueryLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateBigQueryLink") + + __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: analytics_admin.UpdateBigQueryLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.BigQueryLink: + r"""Call the update big query link method over HTTP. + + Args: + request (~.analytics_admin.UpdateBigQueryLinkRequest): + The request object. Request message for + UpdateBigQueryLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.BigQueryLink: + A link between a GA4 Property and + BigQuery project. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{bigquery_link.name=properties/*/bigQueryLinks/*}', + 'body': 'bigquery_link', + }, + ] + request, metadata = self._interceptor.pre_update_big_query_link(request, metadata) + pb_request = analytics_admin.UpdateBigQueryLinkRequest.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 = resources.BigQueryLink() + pb_resp = resources.BigQueryLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_big_query_link(resp) + return resp + + class _UpdateCalculatedMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateCalculatedMetric") + + __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: analytics_admin.UpdateCalculatedMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CalculatedMetric: + r"""Call the update calculated metric method over HTTP. + + Args: + request (~.analytics_admin.UpdateCalculatedMetricRequest): + The request object. Request message for + UpdateCalculatedMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CalculatedMetric: + A definition for a calculated metric. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{calculated_metric.name=properties/*/calculatedMetrics/*}', + 'body': 'calculated_metric', + }, + ] + request, metadata = self._interceptor.pre_update_calculated_metric(request, metadata) + pb_request = analytics_admin.UpdateCalculatedMetricRequest.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 = resources.CalculatedMetric() + pb_resp = resources.CalculatedMetric.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_calculated_metric(resp) + return resp + + class _UpdateChannelGroup(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateChannelGroup") + + __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: analytics_admin.UpdateChannelGroupRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gaa_channel_group.ChannelGroup: + r"""Call the update channel group method over HTTP. + + Args: + request (~.analytics_admin.UpdateChannelGroupRequest): + The request object. Request message for + UpdateChannelGroup RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gaa_channel_group.ChannelGroup: + A resource message representing a + Channel Group. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{channel_group.name=properties/*/channelGroups/*}', + 'body': 'channel_group', + }, + ] + request, metadata = self._interceptor.pre_update_channel_group(request, metadata) + pb_request = analytics_admin.UpdateChannelGroupRequest.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 = gaa_channel_group.ChannelGroup() + pb_resp = gaa_channel_group.ChannelGroup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_channel_group(resp) + return resp + + class _UpdateConversionEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateConversionEvent") + + __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: analytics_admin.UpdateConversionEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ConversionEvent: + r"""Call the update conversion event method over HTTP. + + Args: + request (~.analytics_admin.UpdateConversionEventRequest): + The request object. Request message for + UpdateConversionEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{conversion_event.name=properties/*/conversionEvents/*}', + 'body': 'conversion_event', + }, + ] + request, metadata = self._interceptor.pre_update_conversion_event(request, metadata) + pb_request = analytics_admin.UpdateConversionEventRequest.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 = resources.ConversionEvent() + pb_resp = resources.ConversionEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_conversion_event(resp) + return resp + + class _UpdateCustomDimension(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateCustomDimension") + + __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: analytics_admin.UpdateCustomDimensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomDimension: + r"""Call the update custom dimension method over HTTP. + + Args: + request (~.analytics_admin.UpdateCustomDimensionRequest): + The request object. Request message for + UpdateCustomDimension RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomDimension: + A definition for a CustomDimension. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{custom_dimension.name=properties/*/customDimensions/*}', + 'body': 'custom_dimension', + }, + ] + request, metadata = self._interceptor.pre_update_custom_dimension(request, metadata) + pb_request = analytics_admin.UpdateCustomDimensionRequest.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 = resources.CustomDimension() + pb_resp = resources.CustomDimension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_custom_dimension(resp) + return resp + + class _UpdateCustomMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateCustomMetric") + + __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: analytics_admin.UpdateCustomMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomMetric: + r"""Call the update custom metric method over HTTP. + + Args: + request (~.analytics_admin.UpdateCustomMetricRequest): + The request object. Request message for + UpdateCustomMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomMetric: + A definition for a custom metric. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{custom_metric.name=properties/*/customMetrics/*}', + 'body': 'custom_metric', + }, + ] + request, metadata = self._interceptor.pre_update_custom_metric(request, metadata) + pb_request = analytics_admin.UpdateCustomMetricRequest.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 = resources.CustomMetric() + pb_resp = resources.CustomMetric.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_custom_metric(resp) + return resp + + class _UpdateDataRedactionSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateDataRedactionSettings") + + __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: analytics_admin.UpdateDataRedactionSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataRedactionSettings: + r"""Call the update data redaction + settings method over HTTP. + + Args: + request (~.analytics_admin.UpdateDataRedactionSettingsRequest): + The request object. Request message for + UpdateDataRedactionSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataRedactionSettings: + Settings for client-side data + redaction. Singleton resource under a + Web Stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{data_redaction_settings.name=properties/*/dataStreams/*/dataRedactionSettings}', + 'body': 'data_redaction_settings', + }, + ] + request, metadata = self._interceptor.pre_update_data_redaction_settings(request, metadata) + pb_request = analytics_admin.UpdateDataRedactionSettingsRequest.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 = resources.DataRedactionSettings() + pb_resp = resources.DataRedactionSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_data_redaction_settings(resp) + return resp + + class _UpdateDataRetentionSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateDataRetentionSettings") + + __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: analytics_admin.UpdateDataRetentionSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataRetentionSettings: + r"""Call the update data retention + settings method over HTTP. + + Args: + request (~.analytics_admin.UpdateDataRetentionSettingsRequest): + The request object. Request message for + UpdateDataRetentionSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{data_retention_settings.name=properties/*/dataRetentionSettings}', + 'body': 'data_retention_settings', + }, + ] + request, metadata = self._interceptor.pre_update_data_retention_settings(request, metadata) + pb_request = analytics_admin.UpdateDataRetentionSettingsRequest.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 = resources.DataRetentionSettings() + pb_resp = resources.DataRetentionSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_data_retention_settings(resp) + return resp + + class _UpdateDataStream(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateDataStream") + + __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: analytics_admin.UpdateDataStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataStream: + r"""Call the update data stream method over HTTP. + + Args: + request (~.analytics_admin.UpdateDataStreamRequest): + The request object. Request message for UpdateDataStream + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataStream: + A resource message representing a + data stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{data_stream.name=properties/*/dataStreams/*}', + 'body': 'data_stream', + }, + ] + request, metadata = self._interceptor.pre_update_data_stream(request, metadata) + pb_request = analytics_admin.UpdateDataStreamRequest.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 = resources.DataStream() + pb_resp = resources.DataStream.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_data_stream(resp) + return resp + + class _UpdateDisplayVideo360AdvertiserLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateDisplayVideo360AdvertiserLink") + + __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: analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DisplayVideo360AdvertiserLink: + r"""Call the update display video360 + advertiser link method over HTTP. + + Args: + request (~.analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest): + The request object. Request message for + UpdateDisplayVideo360AdvertiserLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DisplayVideo360AdvertiserLink: + A link between a GA4 property and a + Display & Video 360 advertiser. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{display_video_360_advertiser_link.name=properties/*/displayVideo360AdvertiserLinks/*}', + 'body': 'display_video_360_advertiser_link', + }, + ] + request, metadata = self._interceptor.pre_update_display_video360_advertiser_link(request, metadata) + pb_request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest.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 = resources.DisplayVideo360AdvertiserLink() + pb_resp = resources.DisplayVideo360AdvertiserLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_display_video360_advertiser_link(resp) + return resp + + class _UpdateEnhancedMeasurementSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateEnhancedMeasurementSettings") + + __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: analytics_admin.UpdateEnhancedMeasurementSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.EnhancedMeasurementSettings: + r"""Call the update enhanced + measurement settings method over HTTP. + + Args: + request (~.analytics_admin.UpdateEnhancedMeasurementSettingsRequest): + The request object. Request message for + UpdateEnhancedMeasurementSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.EnhancedMeasurementSettings: + Singleton resource under a web + DataStream, configuring measurement of + additional site interactions and + content. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{enhanced_measurement_settings.name=properties/*/dataStreams/*/enhancedMeasurementSettings}', + 'body': 'enhanced_measurement_settings', + }, + ] + request, metadata = self._interceptor.pre_update_enhanced_measurement_settings(request, metadata) + pb_request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest.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 = resources.EnhancedMeasurementSettings() + pb_resp = resources.EnhancedMeasurementSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_enhanced_measurement_settings(resp) + return resp + + class _UpdateEventCreateRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateEventCreateRule") + + __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: analytics_admin.UpdateEventCreateRuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> event_create_and_edit.EventCreateRule: + r"""Call the update event create rule method over HTTP. + + Args: + request (~.analytics_admin.UpdateEventCreateRuleRequest): + The request object. Request message for + UpdateEventCreateRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_create_and_edit.EventCreateRule: + An Event Create Rule defines + conditions that will trigger the + creation of an entirely new event based + upon matched criteria of a source event. + Additional mutations of the parameters + from the source event can be defined. + + Unlike Event Edit rules, Event Creation + Rules have no defined order. They will + all be run independently. + + Event Edit and Event Create rules can't + be used to modify an event created from + an Event Create rule. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{event_create_rule.name=properties/*/dataStreams/*/eventCreateRules/*}', + 'body': 'event_create_rule', + }, + ] + request, metadata = self._interceptor.pre_update_event_create_rule(request, metadata) + pb_request = analytics_admin.UpdateEventCreateRuleRequest.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 = event_create_and_edit.EventCreateRule() + pb_resp = event_create_and_edit.EventCreateRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_event_create_rule(resp) + return resp + + class _UpdateEventEditRule(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateEventEditRule") + + __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: analytics_admin.UpdateEventEditRuleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> event_create_and_edit.EventEditRule: + r"""Call the update event edit rule method over HTTP. + + Args: + request (~.analytics_admin.UpdateEventEditRuleRequest): + The request object. Request message for + UpdateEventEditRule RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.event_create_and_edit.EventEditRule: + An Event Edit Rule defines conditions + that will trigger the creation of an + entirely new event based upon matched + criteria of a source event. Additional + mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit + Rules are applied in their defined + order. + + Event Edit rules can't be used to modify + an event created from an Event Create + rule. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{event_edit_rule.name=properties/*/dataStreams/*/eventEditRules/*}', + 'body': 'event_edit_rule', + }, + ] + request, metadata = self._interceptor.pre_update_event_edit_rule(request, metadata) + pb_request = analytics_admin.UpdateEventEditRuleRequest.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 = event_create_and_edit.EventEditRule() + pb_resp = event_create_and_edit.EventEditRule.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_event_edit_rule(resp) + return resp + + class _UpdateExpandedDataSet(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateExpandedDataSet") + + __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: analytics_admin.UpdateExpandedDataSetRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gaa_expanded_data_set.ExpandedDataSet: + r"""Call the update expanded data set method over HTTP. + + Args: + request (~.analytics_admin.UpdateExpandedDataSetRequest): + The request object. Request message for + UpdateExpandedDataSet RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gaa_expanded_data_set.ExpandedDataSet: + A resource message representing a GA4 + ExpandedDataSet. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{expanded_data_set.name=properties/*/expandedDataSets/*}', + 'body': 'expanded_data_set', + }, + ] + request, metadata = self._interceptor.pre_update_expanded_data_set(request, metadata) + pb_request = analytics_admin.UpdateExpandedDataSetRequest.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 = gaa_expanded_data_set.ExpandedDataSet() + pb_resp = gaa_expanded_data_set.ExpandedDataSet.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_expanded_data_set(resp) + return resp + + class _UpdateGoogleAdsLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateGoogleAdsLink") + + __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: analytics_admin.UpdateGoogleAdsLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.GoogleAdsLink: + r"""Call the update google ads link method over HTTP. + + Args: + request (~.analytics_admin.UpdateGoogleAdsLinkRequest): + The request object. Request message for + UpdateGoogleAdsLink RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{google_ads_link.name=properties/*/googleAdsLinks/*}', + 'body': 'google_ads_link', + }, + ] + request, metadata = self._interceptor.pre_update_google_ads_link(request, metadata) + pb_request = analytics_admin.UpdateGoogleAdsLinkRequest.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 = resources.GoogleAdsLink() + pb_resp = resources.GoogleAdsLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_google_ads_link(resp) + return resp + + class _UpdateGoogleSignalsSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateGoogleSignalsSettings") + + __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: analytics_admin.UpdateGoogleSignalsSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.GoogleSignalsSettings: + r"""Call the update google signals + settings method over HTTP. + + Args: + request (~.analytics_admin.UpdateGoogleSignalsSettingsRequest): + The request object. Request message for + UpdateGoogleSignalsSettings RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.GoogleSignalsSettings: + Settings values for Google Signals. + This is a singleton resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{google_signals_settings.name=properties/*/googleSignalsSettings}', + 'body': 'google_signals_settings', + }, + ] + request, metadata = self._interceptor.pre_update_google_signals_settings(request, metadata) + pb_request = analytics_admin.UpdateGoogleSignalsSettingsRequest.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 = resources.GoogleSignalsSettings() + pb_resp = resources.GoogleSignalsSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_google_signals_settings(resp) + return resp + + class _UpdateKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateKeyEvent") + + __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: analytics_admin.UpdateKeyEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.KeyEvent: + r"""Call the update key event method over HTTP. + + Args: + request (~.analytics_admin.UpdateKeyEventRequest): + The request object. Request message for UpdateKeyEvent + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.KeyEvent: + A key event in a Google Analytics + property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{key_event.name=properties/*/keyEvents/*}', + 'body': 'key_event', + }, + ] + request, metadata = self._interceptor.pre_update_key_event(request, metadata) + pb_request = analytics_admin.UpdateKeyEventRequest.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 = resources.KeyEvent() + pb_resp = resources.KeyEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_key_event(resp) + return resp + + class _UpdateMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateMeasurementProtocolSecret") + + __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: analytics_admin.UpdateMeasurementProtocolSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.MeasurementProtocolSecret: + r"""Call the update measurement + protocol secret method over HTTP. + + Args: + request (~.analytics_admin.UpdateMeasurementProtocolSecretRequest): + The request object. Request message for + UpdateMeasurementProtocolSecret RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{measurement_protocol_secret.name=properties/*/dataStreams/*/measurementProtocolSecrets/*}', + 'body': 'measurement_protocol_secret', + }, + ] + request, metadata = self._interceptor.pre_update_measurement_protocol_secret(request, metadata) + pb_request = analytics_admin.UpdateMeasurementProtocolSecretRequest.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 = resources.MeasurementProtocolSecret() + pb_resp = resources.MeasurementProtocolSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_measurement_protocol_secret(resp) + return resp + + class _UpdateProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateProperty") + + __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: analytics_admin.UpdatePropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Property: + r"""Call the update property method over HTTP. + + Args: + request (~.analytics_admin.UpdatePropertyRequest): + The request object. Request message for UpdateProperty + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{property.name=properties/*}', + 'body': 'property', + }, + ] + request, metadata = self._interceptor.pre_update_property(request, metadata) + pb_request = analytics_admin.UpdatePropertyRequest.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 = resources.Property() + pb_resp = resources.Property.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_property(resp) + return resp + + class _UpdateSearchAds360Link(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateSearchAds360Link") + + __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: analytics_admin.UpdateSearchAds360LinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.SearchAds360Link: + r"""Call the update search ads360 link method over HTTP. + + Args: + request (~.analytics_admin.UpdateSearchAds360LinkRequest): + The request object. Request message for + UpdateSearchAds360Link RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SearchAds360Link: + A link between a GA4 property and a + Search Ads 360 entity. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{search_ads_360_link.name=properties/*/searchAds360Links/*}', + 'body': 'search_ads_360_link', + }, + ] + request, metadata = self._interceptor.pre_update_search_ads360_link(request, metadata) + pb_request = analytics_admin.UpdateSearchAds360LinkRequest.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 = resources.SearchAds360Link() + pb_resp = resources.SearchAds360Link.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_search_ads360_link(resp) + return resp + + class _UpdateSKAdNetworkConversionValueSchema(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateSKAdNetworkConversionValueSchema") + + __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: analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.SKAdNetworkConversionValueSchema: + r"""Call the update sk ad network + conversion value schema method over HTTP. + + Args: + request (~.analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest): + The request object. Request message for + UpdateSKAdNetworkConversionValueSchema + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.SKAdNetworkConversionValueSchema: + SKAdNetwork conversion value schema + of an iOS stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{skadnetwork_conversion_value_schema.name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}', + 'body': 'skadnetwork_conversion_value_schema', + }, + ] + request, metadata = self._interceptor.pre_update_sk_ad_network_conversion_value_schema(request, metadata) + pb_request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest.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 = resources.SKAdNetworkConversionValueSchema() + pb_resp = resources.SKAdNetworkConversionValueSchema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_sk_ad_network_conversion_value_schema(resp) + return resp + + class _UpdateSubpropertyEventFilter(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateSubpropertyEventFilter") + + __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: analytics_admin.UpdateSubpropertyEventFilterRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> gaa_subproperty_event_filter.SubpropertyEventFilter: + r"""Call the update subproperty event + filter method over HTTP. + + Args: + request (~.analytics_admin.UpdateSubpropertyEventFilterRequest): + The request object. Request message for + UpdateSubpropertyEventFilter RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gaa_subproperty_event_filter.SubpropertyEventFilter: + A resource message representing a GA4 + Subproperty event filter. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1alpha/{subproperty_event_filter.name=properties/*/subpropertyEventFilters/*}', + 'body': 'subproperty_event_filter', + }, + ] + request, metadata = self._interceptor.pre_update_subproperty_event_filter(request, metadata) + pb_request = analytics_admin.UpdateSubpropertyEventFilterRequest.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 = gaa_subproperty_event_filter.SubpropertyEventFilter() + pb_resp = gaa_subproperty_event_filter.SubpropertyEventFilter.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_subproperty_event_filter(resp) + return resp + + @property + def acknowledge_user_data_collection(self) -> Callable[ + [analytics_admin.AcknowledgeUserDataCollectionRequest], + analytics_admin.AcknowledgeUserDataCollectionResponse]: + # 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._AcknowledgeUserDataCollection(self._session, self._host, self._interceptor) # type: ignore + + @property + def approve_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest], + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse]: + # 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._ApproveDisplayVideo360AdvertiserLinkProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def archive_audience(self) -> Callable[ + [analytics_admin.ArchiveAudienceRequest], + 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._ArchiveAudience(self._session, self._host, self._interceptor) # type: ignore + + @property + def archive_custom_dimension(self) -> Callable[ + [analytics_admin.ArchiveCustomDimensionRequest], + 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._ArchiveCustomDimension(self._session, self._host, self._interceptor) # type: ignore + + @property + def archive_custom_metric(self) -> Callable[ + [analytics_admin.ArchiveCustomMetricRequest], + 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._ArchiveCustomMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_create_access_bindings(self) -> Callable[ + [analytics_admin.BatchCreateAccessBindingsRequest], + analytics_admin.BatchCreateAccessBindingsResponse]: + # 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._BatchCreateAccessBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_delete_access_bindings(self) -> Callable[ + [analytics_admin.BatchDeleteAccessBindingsRequest], + 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._BatchDeleteAccessBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_get_access_bindings(self) -> Callable[ + [analytics_admin.BatchGetAccessBindingsRequest], + analytics_admin.BatchGetAccessBindingsResponse]: + # 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._BatchGetAccessBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_update_access_bindings(self) -> Callable[ + [analytics_admin.BatchUpdateAccessBindingsRequest], + analytics_admin.BatchUpdateAccessBindingsResponse]: + # 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._BatchUpdateAccessBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest], + resources.DisplayVideo360AdvertiserLinkProposal]: + # 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._CancelDisplayVideo360AdvertiserLinkProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_access_binding(self) -> Callable[ + [analytics_admin.CreateAccessBindingRequest], + resources.AccessBinding]: + # 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._CreateAccessBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_ad_sense_link(self) -> Callable[ + [analytics_admin.CreateAdSenseLinkRequest], + resources.AdSenseLink]: + # 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._CreateAdSenseLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_audience(self) -> Callable[ + [analytics_admin.CreateAudienceRequest], + gaa_audience.Audience]: + # 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._CreateAudience(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_big_query_link(self) -> Callable[ + [analytics_admin.CreateBigQueryLinkRequest], + resources.BigQueryLink]: + # 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._CreateBigQueryLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_calculated_metric(self) -> Callable[ + [analytics_admin.CreateCalculatedMetricRequest], + resources.CalculatedMetric]: + # 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._CreateCalculatedMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_channel_group(self) -> Callable[ + [analytics_admin.CreateChannelGroupRequest], + gaa_channel_group.ChannelGroup]: + # 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._CreateChannelGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_connected_site_tag(self) -> Callable[ + [analytics_admin.CreateConnectedSiteTagRequest], + analytics_admin.CreateConnectedSiteTagResponse]: + # 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._CreateConnectedSiteTag(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_conversion_event(self) -> Callable[ + [analytics_admin.CreateConversionEventRequest], + resources.ConversionEvent]: + # 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._CreateConversionEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_custom_dimension(self) -> Callable[ + [analytics_admin.CreateCustomDimensionRequest], + resources.CustomDimension]: + # 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._CreateCustomDimension(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_custom_metric(self) -> Callable[ + [analytics_admin.CreateCustomMetricRequest], + resources.CustomMetric]: + # 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._CreateCustomMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_data_stream(self) -> Callable[ + [analytics_admin.CreateDataStreamRequest], + resources.DataStream]: + # 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._CreateDataStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest], + resources.DisplayVideo360AdvertiserLink]: + # 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._CreateDisplayVideo360AdvertiserLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest], + resources.DisplayVideo360AdvertiserLinkProposal]: + # 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._CreateDisplayVideo360AdvertiserLinkProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_event_create_rule(self) -> Callable[ + [analytics_admin.CreateEventCreateRuleRequest], + event_create_and_edit.EventCreateRule]: + # 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._CreateEventCreateRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_event_edit_rule(self) -> Callable[ + [analytics_admin.CreateEventEditRuleRequest], + event_create_and_edit.EventEditRule]: + # 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._CreateEventEditRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_expanded_data_set(self) -> Callable[ + [analytics_admin.CreateExpandedDataSetRequest], + gaa_expanded_data_set.ExpandedDataSet]: + # 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._CreateExpandedDataSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_firebase_link(self) -> Callable[ + [analytics_admin.CreateFirebaseLinkRequest], + resources.FirebaseLink]: + # 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._CreateFirebaseLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_google_ads_link(self) -> Callable[ + [analytics_admin.CreateGoogleAdsLinkRequest], + resources.GoogleAdsLink]: + # 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._CreateGoogleAdsLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_key_event(self) -> Callable[ + [analytics_admin.CreateKeyEventRequest], + resources.KeyEvent]: + # 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._CreateKeyEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.CreateMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + # 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._CreateMeasurementProtocolSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_property(self) -> Callable[ + [analytics_admin.CreatePropertyRequest], + resources.Property]: + # 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._CreateProperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_rollup_property(self) -> Callable[ + [analytics_admin.CreateRollupPropertyRequest], + analytics_admin.CreateRollupPropertyResponse]: + # 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._CreateRollupProperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_rollup_property_source_link(self) -> Callable[ + [analytics_admin.CreateRollupPropertySourceLinkRequest], + resources.RollupPropertySourceLink]: + # 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._CreateRollupPropertySourceLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_search_ads360_link(self) -> Callable[ + [analytics_admin.CreateSearchAds360LinkRequest], + resources.SearchAds360Link]: + # 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._CreateSearchAds360Link(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest], + resources.SKAdNetworkConversionValueSchema]: + # 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._CreateSKAdNetworkConversionValueSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_subproperty_event_filter(self) -> Callable[ + [analytics_admin.CreateSubpropertyEventFilterRequest], + gaa_subproperty_event_filter.SubpropertyEventFilter]: + # 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._CreateSubpropertyEventFilter(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_access_binding(self) -> Callable[ + [analytics_admin.DeleteAccessBindingRequest], + 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._DeleteAccessBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_account(self) -> Callable[ + [analytics_admin.DeleteAccountRequest], + 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._DeleteAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_ad_sense_link(self) -> Callable[ + [analytics_admin.DeleteAdSenseLinkRequest], + 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._DeleteAdSenseLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_big_query_link(self) -> Callable[ + [analytics_admin.DeleteBigQueryLinkRequest], + 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._DeleteBigQueryLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_calculated_metric(self) -> Callable[ + [analytics_admin.DeleteCalculatedMetricRequest], + 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._DeleteCalculatedMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_channel_group(self) -> Callable[ + [analytics_admin.DeleteChannelGroupRequest], + 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._DeleteChannelGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_connected_site_tag(self) -> Callable[ + [analytics_admin.DeleteConnectedSiteTagRequest], + 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._DeleteConnectedSiteTag(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_conversion_event(self) -> Callable[ + [analytics_admin.DeleteConversionEventRequest], + 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._DeleteConversionEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_data_stream(self) -> Callable[ + [analytics_admin.DeleteDataStreamRequest], + 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._DeleteDataStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest], + 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._DeleteDisplayVideo360AdvertiserLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest], + 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._DeleteDisplayVideo360AdvertiserLinkProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_event_create_rule(self) -> Callable[ + [analytics_admin.DeleteEventCreateRuleRequest], + 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._DeleteEventCreateRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_event_edit_rule(self) -> Callable[ + [analytics_admin.DeleteEventEditRuleRequest], + 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._DeleteEventEditRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_expanded_data_set(self) -> Callable[ + [analytics_admin.DeleteExpandedDataSetRequest], + 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._DeleteExpandedDataSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_firebase_link(self) -> Callable[ + [analytics_admin.DeleteFirebaseLinkRequest], + 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._DeleteFirebaseLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_google_ads_link(self) -> Callable[ + [analytics_admin.DeleteGoogleAdsLinkRequest], + 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._DeleteGoogleAdsLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_key_event(self) -> Callable[ + [analytics_admin.DeleteKeyEventRequest], + 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._DeleteKeyEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.DeleteMeasurementProtocolSecretRequest], + 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._DeleteMeasurementProtocolSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_property(self) -> Callable[ + [analytics_admin.DeletePropertyRequest], + resources.Property]: + # 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._DeleteProperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_rollup_property_source_link(self) -> Callable[ + [analytics_admin.DeleteRollupPropertySourceLinkRequest], + 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._DeleteRollupPropertySourceLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_search_ads360_link(self) -> Callable[ + [analytics_admin.DeleteSearchAds360LinkRequest], + 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._DeleteSearchAds360Link(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest], + 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._DeleteSKAdNetworkConversionValueSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_subproperty_event_filter(self) -> Callable[ + [analytics_admin.DeleteSubpropertyEventFilterRequest], + 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._DeleteSubpropertyEventFilter(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_automated_ga4_configuration_opt_out(self) -> Callable[ + [analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest], + analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse]: + # 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._FetchAutomatedGa4ConfigurationOptOut(self._session, self._host, self._interceptor) # type: ignore + + @property + def fetch_connected_ga4_property(self) -> Callable[ + [analytics_admin.FetchConnectedGa4PropertyRequest], + analytics_admin.FetchConnectedGa4PropertyResponse]: + # 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._FetchConnectedGa4Property(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_access_binding(self) -> Callable[ + [analytics_admin.GetAccessBindingRequest], + resources.AccessBinding]: + # 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._GetAccessBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_account(self) -> Callable[ + [analytics_admin.GetAccountRequest], + resources.Account]: + # 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._GetAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_ad_sense_link(self) -> Callable[ + [analytics_admin.GetAdSenseLinkRequest], + resources.AdSenseLink]: + # 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._GetAdSenseLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_attribution_settings(self) -> Callable[ + [analytics_admin.GetAttributionSettingsRequest], + resources.AttributionSettings]: + # 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._GetAttributionSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_audience(self) -> Callable[ + [analytics_admin.GetAudienceRequest], + audience.Audience]: + # 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._GetAudience(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_big_query_link(self) -> Callable[ + [analytics_admin.GetBigQueryLinkRequest], + resources.BigQueryLink]: + # 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._GetBigQueryLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_calculated_metric(self) -> Callable[ + [analytics_admin.GetCalculatedMetricRequest], + resources.CalculatedMetric]: + # 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._GetCalculatedMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_channel_group(self) -> Callable[ + [analytics_admin.GetChannelGroupRequest], + channel_group.ChannelGroup]: + # 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._GetChannelGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_conversion_event(self) -> Callable[ + [analytics_admin.GetConversionEventRequest], + resources.ConversionEvent]: + # 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._GetConversionEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_dimension(self) -> Callable[ + [analytics_admin.GetCustomDimensionRequest], + resources.CustomDimension]: + # 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._GetCustomDimension(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_metric(self) -> Callable[ + [analytics_admin.GetCustomMetricRequest], + resources.CustomMetric]: + # 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._GetCustomMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_redaction_settings(self) -> Callable[ + [analytics_admin.GetDataRedactionSettingsRequest], + resources.DataRedactionSettings]: + # 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._GetDataRedactionSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_retention_settings(self) -> Callable[ + [analytics_admin.GetDataRetentionSettingsRequest], + resources.DataRetentionSettings]: + # 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._GetDataRetentionSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_sharing_settings(self) -> Callable[ + [analytics_admin.GetDataSharingSettingsRequest], + resources.DataSharingSettings]: + # 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._GetDataSharingSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_stream(self) -> Callable[ + [analytics_admin.GetDataStreamRequest], + resources.DataStream]: + # 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._GetDataStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.GetDisplayVideo360AdvertiserLinkRequest], + resources.DisplayVideo360AdvertiserLink]: + # 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._GetDisplayVideo360AdvertiserLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_display_video360_advertiser_link_proposal(self) -> Callable[ + [analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest], + resources.DisplayVideo360AdvertiserLinkProposal]: + # 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._GetDisplayVideo360AdvertiserLinkProposal(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_enhanced_measurement_settings(self) -> Callable[ + [analytics_admin.GetEnhancedMeasurementSettingsRequest], + resources.EnhancedMeasurementSettings]: + # 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._GetEnhancedMeasurementSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_event_create_rule(self) -> Callable[ + [analytics_admin.GetEventCreateRuleRequest], + event_create_and_edit.EventCreateRule]: + # 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._GetEventCreateRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_event_edit_rule(self) -> Callable[ + [analytics_admin.GetEventEditRuleRequest], + event_create_and_edit.EventEditRule]: + # 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._GetEventEditRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_expanded_data_set(self) -> Callable[ + [analytics_admin.GetExpandedDataSetRequest], + expanded_data_set.ExpandedDataSet]: + # 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._GetExpandedDataSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_global_site_tag(self) -> Callable[ + [analytics_admin.GetGlobalSiteTagRequest], + resources.GlobalSiteTag]: + # 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._GetGlobalSiteTag(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_google_signals_settings(self) -> Callable[ + [analytics_admin.GetGoogleSignalsSettingsRequest], + resources.GoogleSignalsSettings]: + # 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._GetGoogleSignalsSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_key_event(self) -> Callable[ + [analytics_admin.GetKeyEventRequest], + resources.KeyEvent]: + # 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._GetKeyEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.GetMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + # 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._GetMeasurementProtocolSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_property(self) -> Callable[ + [analytics_admin.GetPropertyRequest], + resources.Property]: + # 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._GetProperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_rollup_property_source_link(self) -> Callable[ + [analytics_admin.GetRollupPropertySourceLinkRequest], + resources.RollupPropertySourceLink]: + # 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._GetRollupPropertySourceLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_search_ads360_link(self) -> Callable[ + [analytics_admin.GetSearchAds360LinkRequest], + resources.SearchAds360Link]: + # 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._GetSearchAds360Link(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.GetSKAdNetworkConversionValueSchemaRequest], + resources.SKAdNetworkConversionValueSchema]: + # 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._GetSKAdNetworkConversionValueSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_subproperty_event_filter(self) -> Callable[ + [analytics_admin.GetSubpropertyEventFilterRequest], + subproperty_event_filter.SubpropertyEventFilter]: + # 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._GetSubpropertyEventFilter(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_access_bindings(self) -> Callable[ + [analytics_admin.ListAccessBindingsRequest], + analytics_admin.ListAccessBindingsResponse]: + # 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._ListAccessBindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_accounts(self) -> Callable[ + [analytics_admin.ListAccountsRequest], + analytics_admin.ListAccountsResponse]: + # 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._ListAccounts(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_account_summaries(self) -> Callable[ + [analytics_admin.ListAccountSummariesRequest], + analytics_admin.ListAccountSummariesResponse]: + # 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._ListAccountSummaries(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_ad_sense_links(self) -> Callable[ + [analytics_admin.ListAdSenseLinksRequest], + analytics_admin.ListAdSenseLinksResponse]: + # 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._ListAdSenseLinks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_audiences(self) -> Callable[ + [analytics_admin.ListAudiencesRequest], + analytics_admin.ListAudiencesResponse]: + # 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._ListAudiences(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_big_query_links(self) -> Callable[ + [analytics_admin.ListBigQueryLinksRequest], + analytics_admin.ListBigQueryLinksResponse]: + # 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._ListBigQueryLinks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_calculated_metrics(self) -> Callable[ + [analytics_admin.ListCalculatedMetricsRequest], + analytics_admin.ListCalculatedMetricsResponse]: + # 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._ListCalculatedMetrics(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_channel_groups(self) -> Callable[ + [analytics_admin.ListChannelGroupsRequest], + analytics_admin.ListChannelGroupsResponse]: + # 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._ListChannelGroups(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_connected_site_tags(self) -> Callable[ + [analytics_admin.ListConnectedSiteTagsRequest], + analytics_admin.ListConnectedSiteTagsResponse]: + # 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._ListConnectedSiteTags(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_conversion_events(self) -> Callable[ + [analytics_admin.ListConversionEventsRequest], + analytics_admin.ListConversionEventsResponse]: + # 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._ListConversionEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_dimensions(self) -> Callable[ + [analytics_admin.ListCustomDimensionsRequest], + analytics_admin.ListCustomDimensionsResponse]: + # 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._ListCustomDimensions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_metrics(self) -> Callable[ + [analytics_admin.ListCustomMetricsRequest], + analytics_admin.ListCustomMetricsResponse]: + # 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._ListCustomMetrics(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_data_streams(self) -> Callable[ + [analytics_admin.ListDataStreamsRequest], + analytics_admin.ListDataStreamsResponse]: + # 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._ListDataStreams(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_display_video360_advertiser_link_proposals(self) -> Callable[ + [analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest], + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse]: + # 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._ListDisplayVideo360AdvertiserLinkProposals(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_display_video360_advertiser_links(self) -> Callable[ + [analytics_admin.ListDisplayVideo360AdvertiserLinksRequest], + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse]: + # 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._ListDisplayVideo360AdvertiserLinks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_event_create_rules(self) -> Callable[ + [analytics_admin.ListEventCreateRulesRequest], + analytics_admin.ListEventCreateRulesResponse]: + # 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._ListEventCreateRules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_event_edit_rules(self) -> Callable[ + [analytics_admin.ListEventEditRulesRequest], + analytics_admin.ListEventEditRulesResponse]: + # 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._ListEventEditRules(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_expanded_data_sets(self) -> Callable[ + [analytics_admin.ListExpandedDataSetsRequest], + analytics_admin.ListExpandedDataSetsResponse]: + # 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._ListExpandedDataSets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_firebase_links(self) -> Callable[ + [analytics_admin.ListFirebaseLinksRequest], + analytics_admin.ListFirebaseLinksResponse]: + # 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._ListFirebaseLinks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_google_ads_links(self) -> Callable[ + [analytics_admin.ListGoogleAdsLinksRequest], + analytics_admin.ListGoogleAdsLinksResponse]: + # 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._ListGoogleAdsLinks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_key_events(self) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + analytics_admin.ListKeyEventsResponse]: + # 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._ListKeyEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_measurement_protocol_secrets(self) -> Callable[ + [analytics_admin.ListMeasurementProtocolSecretsRequest], + analytics_admin.ListMeasurementProtocolSecretsResponse]: + # 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._ListMeasurementProtocolSecrets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_properties(self) -> Callable[ + [analytics_admin.ListPropertiesRequest], + analytics_admin.ListPropertiesResponse]: + # 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._ListProperties(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_rollup_property_source_links(self) -> Callable[ + [analytics_admin.ListRollupPropertySourceLinksRequest], + analytics_admin.ListRollupPropertySourceLinksResponse]: + # 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._ListRollupPropertySourceLinks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_search_ads360_links(self) -> Callable[ + [analytics_admin.ListSearchAds360LinksRequest], + analytics_admin.ListSearchAds360LinksResponse]: + # 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._ListSearchAds360Links(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sk_ad_network_conversion_value_schemas(self) -> Callable[ + [analytics_admin.ListSKAdNetworkConversionValueSchemasRequest], + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse]: + # 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._ListSKAdNetworkConversionValueSchemas(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_subproperty_event_filters(self) -> Callable[ + [analytics_admin.ListSubpropertyEventFiltersRequest], + analytics_admin.ListSubpropertyEventFiltersResponse]: + # 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._ListSubpropertyEventFilters(self._session, self._host, self._interceptor) # type: ignore + + @property + def provision_account_ticket(self) -> Callable[ + [analytics_admin.ProvisionAccountTicketRequest], + analytics_admin.ProvisionAccountTicketResponse]: + # 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._ProvisionAccountTicket(self._session, self._host, self._interceptor) # type: ignore + + @property + def provision_subproperty(self) -> Callable[ + [analytics_admin.ProvisionSubpropertyRequest], + analytics_admin.ProvisionSubpropertyResponse]: + # 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._ProvisionSubproperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def reorder_event_edit_rules(self) -> Callable[ + [analytics_admin.ReorderEventEditRulesRequest], + 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._ReorderEventEditRules(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_access_report(self) -> Callable[ + [analytics_admin.RunAccessReportRequest], + analytics_admin.RunAccessReportResponse]: + # 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._RunAccessReport(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_change_history_events(self) -> Callable[ + [analytics_admin.SearchChangeHistoryEventsRequest], + analytics_admin.SearchChangeHistoryEventsResponse]: + # 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._SearchChangeHistoryEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_automated_ga4_configuration_opt_out(self) -> Callable[ + [analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest], + analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse]: + # 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._SetAutomatedGa4ConfigurationOptOut(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_access_binding(self) -> Callable[ + [analytics_admin.UpdateAccessBindingRequest], + resources.AccessBinding]: + # 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._UpdateAccessBinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_account(self) -> Callable[ + [analytics_admin.UpdateAccountRequest], + resources.Account]: + # 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._UpdateAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_attribution_settings(self) -> Callable[ + [analytics_admin.UpdateAttributionSettingsRequest], + resources.AttributionSettings]: + # 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._UpdateAttributionSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_audience(self) -> Callable[ + [analytics_admin.UpdateAudienceRequest], + gaa_audience.Audience]: + # 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._UpdateAudience(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_big_query_link(self) -> Callable[ + [analytics_admin.UpdateBigQueryLinkRequest], + resources.BigQueryLink]: + # 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._UpdateBigQueryLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_calculated_metric(self) -> Callable[ + [analytics_admin.UpdateCalculatedMetricRequest], + resources.CalculatedMetric]: + # 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._UpdateCalculatedMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_channel_group(self) -> Callable[ + [analytics_admin.UpdateChannelGroupRequest], + gaa_channel_group.ChannelGroup]: + # 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._UpdateChannelGroup(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_conversion_event(self) -> Callable[ + [analytics_admin.UpdateConversionEventRequest], + resources.ConversionEvent]: + # 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._UpdateConversionEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_dimension(self) -> Callable[ + [analytics_admin.UpdateCustomDimensionRequest], + resources.CustomDimension]: + # 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._UpdateCustomDimension(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_metric(self) -> Callable[ + [analytics_admin.UpdateCustomMetricRequest], + resources.CustomMetric]: + # 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._UpdateCustomMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_redaction_settings(self) -> Callable[ + [analytics_admin.UpdateDataRedactionSettingsRequest], + resources.DataRedactionSettings]: + # 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._UpdateDataRedactionSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_retention_settings(self) -> Callable[ + [analytics_admin.UpdateDataRetentionSettingsRequest], + resources.DataRetentionSettings]: + # 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._UpdateDataRetentionSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_stream(self) -> Callable[ + [analytics_admin.UpdateDataStreamRequest], + resources.DataStream]: + # 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._UpdateDataStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_display_video360_advertiser_link(self) -> Callable[ + [analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest], + resources.DisplayVideo360AdvertiserLink]: + # 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._UpdateDisplayVideo360AdvertiserLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_enhanced_measurement_settings(self) -> Callable[ + [analytics_admin.UpdateEnhancedMeasurementSettingsRequest], + resources.EnhancedMeasurementSettings]: + # 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._UpdateEnhancedMeasurementSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_event_create_rule(self) -> Callable[ + [analytics_admin.UpdateEventCreateRuleRequest], + event_create_and_edit.EventCreateRule]: + # 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._UpdateEventCreateRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_event_edit_rule(self) -> Callable[ + [analytics_admin.UpdateEventEditRuleRequest], + event_create_and_edit.EventEditRule]: + # 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._UpdateEventEditRule(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_expanded_data_set(self) -> Callable[ + [analytics_admin.UpdateExpandedDataSetRequest], + gaa_expanded_data_set.ExpandedDataSet]: + # 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._UpdateExpandedDataSet(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_google_ads_link(self) -> Callable[ + [analytics_admin.UpdateGoogleAdsLinkRequest], + resources.GoogleAdsLink]: + # 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._UpdateGoogleAdsLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_google_signals_settings(self) -> Callable[ + [analytics_admin.UpdateGoogleSignalsSettingsRequest], + resources.GoogleSignalsSettings]: + # 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._UpdateGoogleSignalsSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_key_event(self) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], + resources.KeyEvent]: + # 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._UpdateKeyEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.UpdateMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + # 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._UpdateMeasurementProtocolSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_property(self) -> Callable[ + [analytics_admin.UpdatePropertyRequest], + resources.Property]: + # 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._UpdateProperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_search_ads360_link(self) -> Callable[ + [analytics_admin.UpdateSearchAds360LinkRequest], + resources.SearchAds360Link]: + # 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._UpdateSearchAds360Link(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_sk_ad_network_conversion_value_schema(self) -> Callable[ + [analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest], + resources.SKAdNetworkConversionValueSchema]: + # 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._UpdateSKAdNetworkConversionValueSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_subproperty_event_filter(self) -> Callable[ + [analytics_admin.UpdateSubpropertyEventFilterRequest], + gaa_subproperty_event_filter.SubpropertyEventFilter]: + # 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._UpdateSubpropertyEventFilter(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AnalyticsAdminServiceRestTransport', +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/__init__.py new file mode 100644 index 000000000000..2d396d736fdf --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/__init__.py @@ -0,0 +1,602 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .access_report import ( + AccessBetweenFilter, + AccessDateRange, + AccessDimension, + AccessDimensionHeader, + AccessDimensionValue, + AccessFilter, + AccessFilterExpression, + AccessFilterExpressionList, + AccessInListFilter, + AccessMetric, + AccessMetricHeader, + AccessMetricValue, + AccessNumericFilter, + AccessOrderBy, + AccessQuota, + AccessQuotaStatus, + AccessRow, + AccessStringFilter, + NumericValue, +) +from .analytics_admin import ( + AcknowledgeUserDataCollectionRequest, + AcknowledgeUserDataCollectionResponse, + ApproveDisplayVideo360AdvertiserLinkProposalRequest, + ApproveDisplayVideo360AdvertiserLinkProposalResponse, + ArchiveAudienceRequest, + ArchiveCustomDimensionRequest, + ArchiveCustomMetricRequest, + BatchCreateAccessBindingsRequest, + BatchCreateAccessBindingsResponse, + BatchDeleteAccessBindingsRequest, + BatchGetAccessBindingsRequest, + BatchGetAccessBindingsResponse, + BatchUpdateAccessBindingsRequest, + BatchUpdateAccessBindingsResponse, + CancelDisplayVideo360AdvertiserLinkProposalRequest, + CreateAccessBindingRequest, + CreateAdSenseLinkRequest, + CreateAudienceRequest, + CreateBigQueryLinkRequest, + CreateCalculatedMetricRequest, + CreateChannelGroupRequest, + CreateConnectedSiteTagRequest, + CreateConnectedSiteTagResponse, + CreateConversionEventRequest, + CreateCustomDimensionRequest, + CreateCustomMetricRequest, + CreateDataStreamRequest, + CreateDisplayVideo360AdvertiserLinkProposalRequest, + CreateDisplayVideo360AdvertiserLinkRequest, + CreateEventCreateRuleRequest, + CreateEventEditRuleRequest, + CreateExpandedDataSetRequest, + CreateFirebaseLinkRequest, + CreateGoogleAdsLinkRequest, + CreateKeyEventRequest, + CreateMeasurementProtocolSecretRequest, + CreatePropertyRequest, + CreateRollupPropertyRequest, + CreateRollupPropertyResponse, + CreateRollupPropertySourceLinkRequest, + CreateSearchAds360LinkRequest, + CreateSKAdNetworkConversionValueSchemaRequest, + CreateSubpropertyEventFilterRequest, + DeleteAccessBindingRequest, + DeleteAccountRequest, + DeleteAdSenseLinkRequest, + DeleteBigQueryLinkRequest, + DeleteCalculatedMetricRequest, + DeleteChannelGroupRequest, + DeleteConnectedSiteTagRequest, + DeleteConversionEventRequest, + DeleteDataStreamRequest, + DeleteDisplayVideo360AdvertiserLinkProposalRequest, + DeleteDisplayVideo360AdvertiserLinkRequest, + DeleteEventCreateRuleRequest, + DeleteEventEditRuleRequest, + DeleteExpandedDataSetRequest, + DeleteFirebaseLinkRequest, + DeleteGoogleAdsLinkRequest, + DeleteKeyEventRequest, + DeleteMeasurementProtocolSecretRequest, + DeletePropertyRequest, + DeleteRollupPropertySourceLinkRequest, + DeleteSearchAds360LinkRequest, + DeleteSKAdNetworkConversionValueSchemaRequest, + DeleteSubpropertyEventFilterRequest, + FetchAutomatedGa4ConfigurationOptOutRequest, + FetchAutomatedGa4ConfigurationOptOutResponse, + FetchConnectedGa4PropertyRequest, + FetchConnectedGa4PropertyResponse, + GetAccessBindingRequest, + GetAccountRequest, + GetAdSenseLinkRequest, + GetAttributionSettingsRequest, + GetAudienceRequest, + GetBigQueryLinkRequest, + GetCalculatedMetricRequest, + GetChannelGroupRequest, + GetConversionEventRequest, + GetCustomDimensionRequest, + GetCustomMetricRequest, + GetDataRedactionSettingsRequest, + GetDataRetentionSettingsRequest, + GetDataSharingSettingsRequest, + GetDataStreamRequest, + GetDisplayVideo360AdvertiserLinkProposalRequest, + GetDisplayVideo360AdvertiserLinkRequest, + GetEnhancedMeasurementSettingsRequest, + GetEventCreateRuleRequest, + GetEventEditRuleRequest, + GetExpandedDataSetRequest, + GetGlobalSiteTagRequest, + GetGoogleSignalsSettingsRequest, + GetKeyEventRequest, + GetMeasurementProtocolSecretRequest, + GetPropertyRequest, + GetRollupPropertySourceLinkRequest, + GetSearchAds360LinkRequest, + GetSKAdNetworkConversionValueSchemaRequest, + GetSubpropertyEventFilterRequest, + ListAccessBindingsRequest, + ListAccessBindingsResponse, + ListAccountsRequest, + ListAccountsResponse, + ListAccountSummariesRequest, + ListAccountSummariesResponse, + ListAdSenseLinksRequest, + ListAdSenseLinksResponse, + ListAudiencesRequest, + ListAudiencesResponse, + ListBigQueryLinksRequest, + ListBigQueryLinksResponse, + ListCalculatedMetricsRequest, + ListCalculatedMetricsResponse, + ListChannelGroupsRequest, + ListChannelGroupsResponse, + ListConnectedSiteTagsRequest, + ListConnectedSiteTagsResponse, + ListConversionEventsRequest, + ListConversionEventsResponse, + ListCustomDimensionsRequest, + ListCustomDimensionsResponse, + ListCustomMetricsRequest, + ListCustomMetricsResponse, + ListDataStreamsRequest, + ListDataStreamsResponse, + ListDisplayVideo360AdvertiserLinkProposalsRequest, + ListDisplayVideo360AdvertiserLinkProposalsResponse, + ListDisplayVideo360AdvertiserLinksRequest, + ListDisplayVideo360AdvertiserLinksResponse, + ListEventCreateRulesRequest, + ListEventCreateRulesResponse, + ListEventEditRulesRequest, + ListEventEditRulesResponse, + ListExpandedDataSetsRequest, + ListExpandedDataSetsResponse, + ListFirebaseLinksRequest, + ListFirebaseLinksResponse, + ListGoogleAdsLinksRequest, + ListGoogleAdsLinksResponse, + ListKeyEventsRequest, + ListKeyEventsResponse, + ListMeasurementProtocolSecretsRequest, + ListMeasurementProtocolSecretsResponse, + ListPropertiesRequest, + ListPropertiesResponse, + ListRollupPropertySourceLinksRequest, + ListRollupPropertySourceLinksResponse, + ListSearchAds360LinksRequest, + ListSearchAds360LinksResponse, + ListSKAdNetworkConversionValueSchemasRequest, + ListSKAdNetworkConversionValueSchemasResponse, + ListSubpropertyEventFiltersRequest, + ListSubpropertyEventFiltersResponse, + ProvisionAccountTicketRequest, + ProvisionAccountTicketResponse, + ProvisionSubpropertyRequest, + ProvisionSubpropertyResponse, + ReorderEventEditRulesRequest, + RunAccessReportRequest, + RunAccessReportResponse, + SearchChangeHistoryEventsRequest, + SearchChangeHistoryEventsResponse, + SetAutomatedGa4ConfigurationOptOutRequest, + SetAutomatedGa4ConfigurationOptOutResponse, + UpdateAccessBindingRequest, + UpdateAccountRequest, + UpdateAttributionSettingsRequest, + UpdateAudienceRequest, + UpdateBigQueryLinkRequest, + UpdateCalculatedMetricRequest, + UpdateChannelGroupRequest, + UpdateConversionEventRequest, + UpdateCustomDimensionRequest, + UpdateCustomMetricRequest, + UpdateDataRedactionSettingsRequest, + UpdateDataRetentionSettingsRequest, + UpdateDataStreamRequest, + UpdateDisplayVideo360AdvertiserLinkRequest, + UpdateEnhancedMeasurementSettingsRequest, + UpdateEventCreateRuleRequest, + UpdateEventEditRuleRequest, + UpdateExpandedDataSetRequest, + UpdateGoogleAdsLinkRequest, + UpdateGoogleSignalsSettingsRequest, + UpdateKeyEventRequest, + UpdateMeasurementProtocolSecretRequest, + UpdatePropertyRequest, + UpdateSearchAds360LinkRequest, + UpdateSKAdNetworkConversionValueSchemaRequest, + UpdateSubpropertyEventFilterRequest, +) +from .audience import ( + Audience, + AudienceDimensionOrMetricFilter, + AudienceEventFilter, + AudienceEventTrigger, + AudienceFilterClause, + AudienceFilterExpression, + AudienceFilterExpressionList, + AudienceSequenceFilter, + AudienceSimpleFilter, + AudienceFilterScope, +) +from .channel_group import ( + ChannelGroup, + ChannelGroupFilter, + ChannelGroupFilterExpression, + ChannelGroupFilterExpressionList, + GroupingRule, +) +from .event_create_and_edit import ( + EventCreateRule, + EventEditRule, + MatchingCondition, + ParameterMutation, +) +from .expanded_data_set import ( + ExpandedDataSet, + ExpandedDataSetFilter, + ExpandedDataSetFilterExpression, + ExpandedDataSetFilterExpressionList, +) +from .resources import ( + AccessBinding, + Account, + AccountSummary, + AdSenseLink, + AttributionSettings, + BigQueryLink, + CalculatedMetric, + ChangeHistoryChange, + ChangeHistoryEvent, + ConnectedSiteTag, + ConversionEvent, + ConversionValues, + CustomDimension, + CustomMetric, + DataRedactionSettings, + DataRetentionSettings, + DataSharingSettings, + DataStream, + DisplayVideo360AdvertiserLink, + DisplayVideo360AdvertiserLinkProposal, + EnhancedMeasurementSettings, + EventMapping, + FirebaseLink, + GlobalSiteTag, + GoogleAdsLink, + GoogleSignalsSettings, + KeyEvent, + LinkProposalStatusDetails, + MeasurementProtocolSecret, + PostbackWindow, + Property, + PropertySummary, + RollupPropertySourceLink, + SearchAds360Link, + SKAdNetworkConversionValueSchema, + ActionType, + ActorType, + ChangeHistoryResourceType, + CoarseValue, + GoogleSignalsConsent, + GoogleSignalsState, + IndustryCategory, + LinkProposalInitiatingProduct, + LinkProposalState, + PropertyType, + ServiceLevel, +) +from .subproperty_event_filter import ( + SubpropertyEventFilter, + SubpropertyEventFilterClause, + SubpropertyEventFilterCondition, + SubpropertyEventFilterExpression, + SubpropertyEventFilterExpressionList, +) + +__all__ = ( + 'AccessBetweenFilter', + 'AccessDateRange', + 'AccessDimension', + 'AccessDimensionHeader', + 'AccessDimensionValue', + 'AccessFilter', + 'AccessFilterExpression', + 'AccessFilterExpressionList', + 'AccessInListFilter', + 'AccessMetric', + 'AccessMetricHeader', + 'AccessMetricValue', + 'AccessNumericFilter', + 'AccessOrderBy', + 'AccessQuota', + 'AccessQuotaStatus', + 'AccessRow', + 'AccessStringFilter', + 'NumericValue', + 'AcknowledgeUserDataCollectionRequest', + 'AcknowledgeUserDataCollectionResponse', + 'ApproveDisplayVideo360AdvertiserLinkProposalRequest', + 'ApproveDisplayVideo360AdvertiserLinkProposalResponse', + 'ArchiveAudienceRequest', + 'ArchiveCustomDimensionRequest', + 'ArchiveCustomMetricRequest', + 'BatchCreateAccessBindingsRequest', + 'BatchCreateAccessBindingsResponse', + 'BatchDeleteAccessBindingsRequest', + 'BatchGetAccessBindingsRequest', + 'BatchGetAccessBindingsResponse', + 'BatchUpdateAccessBindingsRequest', + 'BatchUpdateAccessBindingsResponse', + 'CancelDisplayVideo360AdvertiserLinkProposalRequest', + 'CreateAccessBindingRequest', + 'CreateAdSenseLinkRequest', + 'CreateAudienceRequest', + 'CreateBigQueryLinkRequest', + 'CreateCalculatedMetricRequest', + 'CreateChannelGroupRequest', + 'CreateConnectedSiteTagRequest', + 'CreateConnectedSiteTagResponse', + 'CreateConversionEventRequest', + 'CreateCustomDimensionRequest', + 'CreateCustomMetricRequest', + 'CreateDataStreamRequest', + 'CreateDisplayVideo360AdvertiserLinkProposalRequest', + 'CreateDisplayVideo360AdvertiserLinkRequest', + 'CreateEventCreateRuleRequest', + 'CreateEventEditRuleRequest', + 'CreateExpandedDataSetRequest', + 'CreateFirebaseLinkRequest', + 'CreateGoogleAdsLinkRequest', + 'CreateKeyEventRequest', + 'CreateMeasurementProtocolSecretRequest', + 'CreatePropertyRequest', + 'CreateRollupPropertyRequest', + 'CreateRollupPropertyResponse', + 'CreateRollupPropertySourceLinkRequest', + 'CreateSearchAds360LinkRequest', + 'CreateSKAdNetworkConversionValueSchemaRequest', + 'CreateSubpropertyEventFilterRequest', + 'DeleteAccessBindingRequest', + 'DeleteAccountRequest', + 'DeleteAdSenseLinkRequest', + 'DeleteBigQueryLinkRequest', + 'DeleteCalculatedMetricRequest', + 'DeleteChannelGroupRequest', + 'DeleteConnectedSiteTagRequest', + 'DeleteConversionEventRequest', + 'DeleteDataStreamRequest', + 'DeleteDisplayVideo360AdvertiserLinkProposalRequest', + 'DeleteDisplayVideo360AdvertiserLinkRequest', + 'DeleteEventCreateRuleRequest', + 'DeleteEventEditRuleRequest', + 'DeleteExpandedDataSetRequest', + 'DeleteFirebaseLinkRequest', + 'DeleteGoogleAdsLinkRequest', + 'DeleteKeyEventRequest', + 'DeleteMeasurementProtocolSecretRequest', + 'DeletePropertyRequest', + 'DeleteRollupPropertySourceLinkRequest', + 'DeleteSearchAds360LinkRequest', + 'DeleteSKAdNetworkConversionValueSchemaRequest', + 'DeleteSubpropertyEventFilterRequest', + 'FetchAutomatedGa4ConfigurationOptOutRequest', + 'FetchAutomatedGa4ConfigurationOptOutResponse', + 'FetchConnectedGa4PropertyRequest', + 'FetchConnectedGa4PropertyResponse', + 'GetAccessBindingRequest', + 'GetAccountRequest', + 'GetAdSenseLinkRequest', + 'GetAttributionSettingsRequest', + 'GetAudienceRequest', + 'GetBigQueryLinkRequest', + 'GetCalculatedMetricRequest', + 'GetChannelGroupRequest', + 'GetConversionEventRequest', + 'GetCustomDimensionRequest', + 'GetCustomMetricRequest', + 'GetDataRedactionSettingsRequest', + 'GetDataRetentionSettingsRequest', + 'GetDataSharingSettingsRequest', + 'GetDataStreamRequest', + 'GetDisplayVideo360AdvertiserLinkProposalRequest', + 'GetDisplayVideo360AdvertiserLinkRequest', + 'GetEnhancedMeasurementSettingsRequest', + 'GetEventCreateRuleRequest', + 'GetEventEditRuleRequest', + 'GetExpandedDataSetRequest', + 'GetGlobalSiteTagRequest', + 'GetGoogleSignalsSettingsRequest', + 'GetKeyEventRequest', + 'GetMeasurementProtocolSecretRequest', + 'GetPropertyRequest', + 'GetRollupPropertySourceLinkRequest', + 'GetSearchAds360LinkRequest', + 'GetSKAdNetworkConversionValueSchemaRequest', + 'GetSubpropertyEventFilterRequest', + 'ListAccessBindingsRequest', + 'ListAccessBindingsResponse', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListAccountSummariesRequest', + 'ListAccountSummariesResponse', + 'ListAdSenseLinksRequest', + 'ListAdSenseLinksResponse', + 'ListAudiencesRequest', + 'ListAudiencesResponse', + 'ListBigQueryLinksRequest', + 'ListBigQueryLinksResponse', + 'ListCalculatedMetricsRequest', + 'ListCalculatedMetricsResponse', + 'ListChannelGroupsRequest', + 'ListChannelGroupsResponse', + 'ListConnectedSiteTagsRequest', + 'ListConnectedSiteTagsResponse', + 'ListConversionEventsRequest', + 'ListConversionEventsResponse', + 'ListCustomDimensionsRequest', + 'ListCustomDimensionsResponse', + 'ListCustomMetricsRequest', + 'ListCustomMetricsResponse', + 'ListDataStreamsRequest', + 'ListDataStreamsResponse', + 'ListDisplayVideo360AdvertiserLinkProposalsRequest', + 'ListDisplayVideo360AdvertiserLinkProposalsResponse', + 'ListDisplayVideo360AdvertiserLinksRequest', + 'ListDisplayVideo360AdvertiserLinksResponse', + 'ListEventCreateRulesRequest', + 'ListEventCreateRulesResponse', + 'ListEventEditRulesRequest', + 'ListEventEditRulesResponse', + 'ListExpandedDataSetsRequest', + 'ListExpandedDataSetsResponse', + 'ListFirebaseLinksRequest', + 'ListFirebaseLinksResponse', + 'ListGoogleAdsLinksRequest', + 'ListGoogleAdsLinksResponse', + 'ListKeyEventsRequest', + 'ListKeyEventsResponse', + 'ListMeasurementProtocolSecretsRequest', + 'ListMeasurementProtocolSecretsResponse', + 'ListPropertiesRequest', + 'ListPropertiesResponse', + 'ListRollupPropertySourceLinksRequest', + 'ListRollupPropertySourceLinksResponse', + 'ListSearchAds360LinksRequest', + 'ListSearchAds360LinksResponse', + 'ListSKAdNetworkConversionValueSchemasRequest', + 'ListSKAdNetworkConversionValueSchemasResponse', + 'ListSubpropertyEventFiltersRequest', + 'ListSubpropertyEventFiltersResponse', + 'ProvisionAccountTicketRequest', + 'ProvisionAccountTicketResponse', + 'ProvisionSubpropertyRequest', + 'ProvisionSubpropertyResponse', + 'ReorderEventEditRulesRequest', + 'RunAccessReportRequest', + 'RunAccessReportResponse', + 'SearchChangeHistoryEventsRequest', + 'SearchChangeHistoryEventsResponse', + 'SetAutomatedGa4ConfigurationOptOutRequest', + 'SetAutomatedGa4ConfigurationOptOutResponse', + 'UpdateAccessBindingRequest', + 'UpdateAccountRequest', + 'UpdateAttributionSettingsRequest', + 'UpdateAudienceRequest', + 'UpdateBigQueryLinkRequest', + 'UpdateCalculatedMetricRequest', + 'UpdateChannelGroupRequest', + 'UpdateConversionEventRequest', + 'UpdateCustomDimensionRequest', + 'UpdateCustomMetricRequest', + 'UpdateDataRedactionSettingsRequest', + 'UpdateDataRetentionSettingsRequest', + 'UpdateDataStreamRequest', + 'UpdateDisplayVideo360AdvertiserLinkRequest', + 'UpdateEnhancedMeasurementSettingsRequest', + 'UpdateEventCreateRuleRequest', + 'UpdateEventEditRuleRequest', + 'UpdateExpandedDataSetRequest', + 'UpdateGoogleAdsLinkRequest', + 'UpdateGoogleSignalsSettingsRequest', + 'UpdateKeyEventRequest', + 'UpdateMeasurementProtocolSecretRequest', + 'UpdatePropertyRequest', + 'UpdateSearchAds360LinkRequest', + 'UpdateSKAdNetworkConversionValueSchemaRequest', + 'UpdateSubpropertyEventFilterRequest', + 'Audience', + 'AudienceDimensionOrMetricFilter', + 'AudienceEventFilter', + 'AudienceEventTrigger', + 'AudienceFilterClause', + 'AudienceFilterExpression', + 'AudienceFilterExpressionList', + 'AudienceSequenceFilter', + 'AudienceSimpleFilter', + 'AudienceFilterScope', + 'ChannelGroup', + 'ChannelGroupFilter', + 'ChannelGroupFilterExpression', + 'ChannelGroupFilterExpressionList', + 'GroupingRule', + 'EventCreateRule', + 'EventEditRule', + 'MatchingCondition', + 'ParameterMutation', + 'ExpandedDataSet', + 'ExpandedDataSetFilter', + 'ExpandedDataSetFilterExpression', + 'ExpandedDataSetFilterExpressionList', + 'AccessBinding', + 'Account', + 'AccountSummary', + 'AdSenseLink', + 'AttributionSettings', + 'BigQueryLink', + 'CalculatedMetric', + 'ChangeHistoryChange', + 'ChangeHistoryEvent', + 'ConnectedSiteTag', + 'ConversionEvent', + 'ConversionValues', + 'CustomDimension', + 'CustomMetric', + 'DataRedactionSettings', + 'DataRetentionSettings', + 'DataSharingSettings', + 'DataStream', + 'DisplayVideo360AdvertiserLink', + 'DisplayVideo360AdvertiserLinkProposal', + 'EnhancedMeasurementSettings', + 'EventMapping', + 'FirebaseLink', + 'GlobalSiteTag', + 'GoogleAdsLink', + 'GoogleSignalsSettings', + 'KeyEvent', + 'LinkProposalStatusDetails', + 'MeasurementProtocolSecret', + 'PostbackWindow', + 'Property', + 'PropertySummary', + 'RollupPropertySourceLink', + 'SearchAds360Link', + 'SKAdNetworkConversionValueSchema', + 'ActionType', + 'ActorType', + 'ChangeHistoryResourceType', + 'CoarseValue', + 'GoogleSignalsConsent', + 'GoogleSignalsState', + 'IndustryCategory', + 'LinkProposalInitiatingProduct', + 'LinkProposalState', + 'PropertyType', + 'ServiceLevel', + 'SubpropertyEventFilter', + 'SubpropertyEventFilterClause', + 'SubpropertyEventFilterCondition', + 'SubpropertyEventFilterExpression', + 'SubpropertyEventFilterExpressionList', +) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/access_report.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/access_report.py new file mode 100644 index 000000000000..198f22bbbbfe --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/access_report.py @@ -0,0 +1,703 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin.v1alpha', + manifest={ + 'AccessDimension', + 'AccessMetric', + 'AccessDateRange', + 'AccessFilterExpression', + 'AccessFilterExpressionList', + 'AccessFilter', + 'AccessStringFilter', + 'AccessInListFilter', + 'AccessNumericFilter', + 'AccessBetweenFilter', + 'NumericValue', + 'AccessOrderBy', + 'AccessDimensionHeader', + 'AccessMetricHeader', + 'AccessRow', + 'AccessDimensionValue', + 'AccessMetricValue', + 'AccessQuota', + 'AccessQuotaStatus', + }, +) + + +class AccessDimension(proto.Message): + r"""Dimensions are attributes of your data. For example, the dimension + ``userEmail`` indicates the email of the user that accessed + reporting data. Dimension values in report responses are strings. + + Attributes: + dimension_name (str): + The API name of the dimension. See `Data Access + Schema `__ + for the list of dimensions supported in this API. + + Dimensions are referenced by name in ``dimensionFilter`` and + ``orderBys``. + """ + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessMetric(proto.Message): + r"""The quantitative measurements of a report. For example, the metric + ``accessCount`` is the total number of data access records. + + Attributes: + metric_name (str): + The API name of the metric. See `Data Access + Schema `__ + for the list of metrics supported in this API. + + Metrics are referenced by name in ``metricFilter`` & + ``orderBys``. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessDateRange(proto.Message): + r"""A contiguous range of days: startDate, startDate + 1, ..., + endDate. + + Attributes: + start_date (str): + The inclusive start date for the query in the format + ``YYYY-MM-DD``. Cannot be after ``endDate``. The format + ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, + and in that case, the date is inferred based on the current + time in the request's time zone. + end_date (str): + The inclusive end date for the query in the format + ``YYYY-MM-DD``. Cannot be before ``startDate``. The format + ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, + and in that case, the date is inferred based on the current + time in the request's time zone. + """ + + start_date: str = proto.Field( + proto.STRING, + number=1, + ) + end_date: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AccessFilterExpression(proto.Message): + r"""Expresses dimension or metric filters. The fields in the same + expression need to be either all dimensions or all metrics. + + 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: + and_group (google.analytics.admin_v1alpha.types.AccessFilterExpressionList): + Each of the FilterExpressions in the and_group has an AND + relationship. + + This field is a member of `oneof`_ ``one_expression``. + or_group (google.analytics.admin_v1alpha.types.AccessFilterExpressionList): + Each of the FilterExpressions in the or_group has an OR + relationship. + + This field is a member of `oneof`_ ``one_expression``. + not_expression (google.analytics.admin_v1alpha.types.AccessFilterExpression): + The FilterExpression is NOT of not_expression. + + This field is a member of `oneof`_ ``one_expression``. + access_filter (google.analytics.admin_v1alpha.types.AccessFilter): + A primitive filter. In the same + FilterExpression, all of the filter's field + names need to be either all dimensions or all + metrics. + + This field is a member of `oneof`_ ``one_expression``. + """ + + and_group: 'AccessFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='one_expression', + message='AccessFilterExpressionList', + ) + or_group: 'AccessFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='one_expression', + message='AccessFilterExpressionList', + ) + not_expression: 'AccessFilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_expression', + message='AccessFilterExpression', + ) + access_filter: 'AccessFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_expression', + message='AccessFilter', + ) + + +class AccessFilterExpressionList(proto.Message): + r"""A list of filter expressions. + + Attributes: + expressions (MutableSequence[google.analytics.admin_v1alpha.types.AccessFilterExpression]): + A list of filter expressions. + """ + + expressions: MutableSequence['AccessFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AccessFilterExpression', + ) + + +class AccessFilter(proto.Message): + r"""An expression to filter dimension or metric values. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_filter (google.analytics.admin_v1alpha.types.AccessStringFilter): + Strings related filter. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.admin_v1alpha.types.AccessInListFilter): + A filter for in list values. + + This field is a member of `oneof`_ ``one_filter``. + numeric_filter (google.analytics.admin_v1alpha.types.AccessNumericFilter): + A filter for numeric or date values. + + This field is a member of `oneof`_ ``one_filter``. + between_filter (google.analytics.admin_v1alpha.types.AccessBetweenFilter): + A filter for two values. + + This field is a member of `oneof`_ ``one_filter``. + field_name (str): + The dimension name or metric name. + """ + + string_filter: 'AccessStringFilter' = proto.Field( + proto.MESSAGE, + number=2, + oneof='one_filter', + message='AccessStringFilter', + ) + in_list_filter: 'AccessInListFilter' = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_filter', + message='AccessInListFilter', + ) + numeric_filter: 'AccessNumericFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_filter', + message='AccessNumericFilter', + ) + between_filter: 'AccessBetweenFilter' = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_filter', + message='AccessBetweenFilter', + ) + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessStringFilter(proto.Message): + r"""The filter for strings. + + Attributes: + match_type (google.analytics.admin_v1alpha.types.AccessStringFilter.MatchType): + The match type for this filter. + value (str): + The string value used for the matching. + case_sensitive (bool): + If true, the string value is case sensitive. + """ + class MatchType(proto.Enum): + r"""The match type of a string filter. + + Values: + MATCH_TYPE_UNSPECIFIED (0): + Unspecified + EXACT (1): + Exact match of the string value. + BEGINS_WITH (2): + Begins with the string value. + ENDS_WITH (3): + Ends with the string value. + CONTAINS (4): + Contains the string value. + FULL_REGEXP (5): + Full match for the regular expression with + the string value. + PARTIAL_REGEXP (6): + Partial match for the regular expression with + the string value. + """ + MATCH_TYPE_UNSPECIFIED = 0 + EXACT = 1 + BEGINS_WITH = 2 + ENDS_WITH = 3 + CONTAINS = 4 + FULL_REGEXP = 5 + PARTIAL_REGEXP = 6 + + match_type: MatchType = proto.Field( + proto.ENUM, + number=1, + enum=MatchType, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class AccessInListFilter(proto.Message): + r"""The result needs to be in a list of string values. + + Attributes: + values (MutableSequence[str]): + The list of string values. Must be non-empty. + case_sensitive (bool): + If true, the string value is case sensitive. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class AccessNumericFilter(proto.Message): + r"""Filters for numeric or date values. + + Attributes: + operation (google.analytics.admin_v1alpha.types.AccessNumericFilter.Operation): + The operation type for this filter. + value (google.analytics.admin_v1alpha.types.NumericValue): + A numeric value or a date value. + """ + class Operation(proto.Enum): + r"""The operation applied to a numeric filter. + + Values: + OPERATION_UNSPECIFIED (0): + Unspecified. + EQUAL (1): + Equal + LESS_THAN (2): + Less than + LESS_THAN_OR_EQUAL (3): + Less than or equal + GREATER_THAN (4): + Greater than + GREATER_THAN_OR_EQUAL (5): + Greater than or equal + """ + OPERATION_UNSPECIFIED = 0 + EQUAL = 1 + LESS_THAN = 2 + LESS_THAN_OR_EQUAL = 3 + GREATER_THAN = 4 + GREATER_THAN_OR_EQUAL = 5 + + operation: Operation = proto.Field( + proto.ENUM, + number=1, + enum=Operation, + ) + value: 'NumericValue' = proto.Field( + proto.MESSAGE, + number=2, + message='NumericValue', + ) + + +class AccessBetweenFilter(proto.Message): + r"""To express that the result needs to be between two numbers + (inclusive). + + Attributes: + from_value (google.analytics.admin_v1alpha.types.NumericValue): + Begins with this number. + to_value (google.analytics.admin_v1alpha.types.NumericValue): + Ends with this number. + """ + + from_value: 'NumericValue' = proto.Field( + proto.MESSAGE, + number=1, + message='NumericValue', + ) + to_value: 'NumericValue' = proto.Field( + proto.MESSAGE, + number=2, + message='NumericValue', + ) + + +class NumericValue(proto.Message): + r"""To represent a number. + + 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: + int64_value (int): + Integer value + + This field is a member of `oneof`_ ``one_value``. + double_value (float): + Double value + + This field is a member of `oneof`_ ``one_value``. + """ + + int64_value: int = proto.Field( + proto.INT64, + number=1, + oneof='one_value', + ) + double_value: float = proto.Field( + proto.DOUBLE, + number=2, + oneof='one_value', + ) + + +class AccessOrderBy(proto.Message): + r"""Order bys define how rows will be sorted in the response. For + example, ordering rows by descending access count is one + ordering, and ordering rows by the country string is a different + ordering. + + 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: + metric (google.analytics.admin_v1alpha.types.AccessOrderBy.MetricOrderBy): + Sorts results by a metric's values. + + This field is a member of `oneof`_ ``one_order_by``. + dimension (google.analytics.admin_v1alpha.types.AccessOrderBy.DimensionOrderBy): + Sorts results by a dimension's values. + + This field is a member of `oneof`_ ``one_order_by``. + desc (bool): + If true, sorts by descending order. If false + or unspecified, sorts in ascending order. + """ + + class MetricOrderBy(proto.Message): + r"""Sorts by metric values. + + Attributes: + metric_name (str): + A metric name in the request to order by. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class DimensionOrderBy(proto.Message): + r"""Sorts by dimension values. + + Attributes: + dimension_name (str): + A dimension name in the request to order by. + order_type (google.analytics.admin_v1alpha.types.AccessOrderBy.DimensionOrderBy.OrderType): + Controls the rule for dimension value + ordering. + """ + class OrderType(proto.Enum): + r"""Rule to order the string dimension values by. + + Values: + ORDER_TYPE_UNSPECIFIED (0): + Unspecified. + ALPHANUMERIC (1): + Alphanumeric sort by Unicode code point. For + example, "2" < "A" < "X" < "b" < "z". + CASE_INSENSITIVE_ALPHANUMERIC (2): + Case insensitive alphanumeric sort by lower + case Unicode code point. For example, "2" < "A" + < "b" < "X" < "z". + NUMERIC (3): + Dimension values are converted to numbers before sorting. + For example in NUMERIC sort, "25" < "100", and in + ``ALPHANUMERIC`` sort, "100" < "25". Non-numeric dimension + values all have equal ordering value below all numeric + values. + """ + ORDER_TYPE_UNSPECIFIED = 0 + ALPHANUMERIC = 1 + CASE_INSENSITIVE_ALPHANUMERIC = 2 + NUMERIC = 3 + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + order_type: 'AccessOrderBy.DimensionOrderBy.OrderType' = proto.Field( + proto.ENUM, + number=2, + enum='AccessOrderBy.DimensionOrderBy.OrderType', + ) + + metric: MetricOrderBy = proto.Field( + proto.MESSAGE, + number=1, + oneof='one_order_by', + message=MetricOrderBy, + ) + dimension: DimensionOrderBy = proto.Field( + proto.MESSAGE, + number=2, + oneof='one_order_by', + message=DimensionOrderBy, + ) + desc: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class AccessDimensionHeader(proto.Message): + r"""Describes a dimension column in the report. Dimensions + requested in a report produce column entries within rows and + DimensionHeaders. However, dimensions used exclusively within + filters or expressions do not produce columns in a report; + correspondingly, those dimensions do not produce headers. + + Attributes: + dimension_name (str): + The dimension's name; for example + 'userEmail'. + """ + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessMetricHeader(proto.Message): + r"""Describes a metric column in the report. Visible metrics + requested in a report produce column entries within rows and + MetricHeaders. However, metrics used exclusively within filters + or expressions do not produce columns in a report; + correspondingly, those metrics do not produce headers. + + Attributes: + metric_name (str): + The metric's name; for example 'accessCount'. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessRow(proto.Message): + r"""Access report data for each row. + + Attributes: + dimension_values (MutableSequence[google.analytics.admin_v1alpha.types.AccessDimensionValue]): + List of dimension values. These values are in + the same order as specified in the request. + metric_values (MutableSequence[google.analytics.admin_v1alpha.types.AccessMetricValue]): + List of metric values. These values are in + the same order as specified in the request. + """ + + dimension_values: MutableSequence['AccessDimensionValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AccessDimensionValue', + ) + metric_values: MutableSequence['AccessMetricValue'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AccessMetricValue', + ) + + +class AccessDimensionValue(proto.Message): + r"""The value of a dimension. + + Attributes: + value (str): + The dimension value. For example, this value + may be 'France' for the 'country' dimension. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessMetricValue(proto.Message): + r"""The value of a metric. + + Attributes: + value (str): + The measurement value. For example, this + value may be '13'. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessQuota(proto.Message): + r"""Current state of all quotas for this Analytics property. If + any quota for a property is exhausted, all requests to that + property will return Resource Exhausted errors. + + Attributes: + tokens_per_day (google.analytics.admin_v1alpha.types.AccessQuotaStatus): + Properties can use 250,000 tokens per day. + Most requests consume fewer than 10 tokens. + tokens_per_hour (google.analytics.admin_v1alpha.types.AccessQuotaStatus): + Properties can use 50,000 tokens per hour. An + API request consumes a single number of tokens, + and that number is deducted from all of the + hourly, daily, and per project hourly quotas. + concurrent_requests (google.analytics.admin_v1alpha.types.AccessQuotaStatus): + Properties can use up to 50 concurrent + requests. + server_errors_per_project_per_hour (google.analytics.admin_v1alpha.types.AccessQuotaStatus): + Properties and cloud project pairs can have + up to 50 server errors per hour. + tokens_per_project_per_hour (google.analytics.admin_v1alpha.types.AccessQuotaStatus): + Properties can use up to 25% of their tokens + per project per hour. This amounts to Analytics + 360 Properties can use 12,500 tokens per project + per hour. An API request consumes a single + number of tokens, and that number is deducted + from all of the hourly, daily, and per project + hourly quotas. + """ + + tokens_per_day: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=1, + message='AccessQuotaStatus', + ) + tokens_per_hour: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=2, + message='AccessQuotaStatus', + ) + concurrent_requests: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=3, + message='AccessQuotaStatus', + ) + server_errors_per_project_per_hour: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=4, + message='AccessQuotaStatus', + ) + tokens_per_project_per_hour: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=5, + message='AccessQuotaStatus', + ) + + +class AccessQuotaStatus(proto.Message): + r"""Current state for a particular quota group. + + Attributes: + consumed (int): + Quota consumed by this request. + remaining (int): + Quota remaining after this request. + """ + + consumed: int = proto.Field( + proto.INT32, + number=1, + ) + remaining: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/analytics_admin.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/analytics_admin.py new file mode 100644 index 000000000000..baf84c96f9ad --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/analytics_admin.py @@ -0,0 +1,4937 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1alpha.types import access_report +from google.analytics.admin_v1alpha.types import audience as gaa_audience +from google.analytics.admin_v1alpha.types import channel_group as gaa_channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set as gaa_expanded_data_set +from google.analytics.admin_v1alpha.types import resources +from google.analytics.admin_v1alpha.types import subproperty_event_filter as gaa_subproperty_event_filter +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.analytics.admin.v1alpha', + manifest={ + 'RunAccessReportRequest', + 'RunAccessReportResponse', + 'GetAccountRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'DeleteAccountRequest', + 'UpdateAccountRequest', + 'ProvisionAccountTicketRequest', + 'ProvisionAccountTicketResponse', + 'GetPropertyRequest', + 'ListPropertiesRequest', + 'ListPropertiesResponse', + 'UpdatePropertyRequest', + 'CreatePropertyRequest', + 'DeletePropertyRequest', + 'CreateFirebaseLinkRequest', + 'DeleteFirebaseLinkRequest', + 'ListFirebaseLinksRequest', + 'ListFirebaseLinksResponse', + 'GetGlobalSiteTagRequest', + 'CreateGoogleAdsLinkRequest', + 'UpdateGoogleAdsLinkRequest', + 'DeleteGoogleAdsLinkRequest', + 'ListGoogleAdsLinksRequest', + 'ListGoogleAdsLinksResponse', + 'GetDataSharingSettingsRequest', + 'ListAccountSummariesRequest', + 'ListAccountSummariesResponse', + 'AcknowledgeUserDataCollectionRequest', + 'AcknowledgeUserDataCollectionResponse', + 'SearchChangeHistoryEventsRequest', + 'SearchChangeHistoryEventsResponse', + 'GetMeasurementProtocolSecretRequest', + 'CreateMeasurementProtocolSecretRequest', + 'DeleteMeasurementProtocolSecretRequest', + 'UpdateMeasurementProtocolSecretRequest', + 'ListMeasurementProtocolSecretsRequest', + 'ListMeasurementProtocolSecretsResponse', + 'GetSKAdNetworkConversionValueSchemaRequest', + 'CreateSKAdNetworkConversionValueSchemaRequest', + 'DeleteSKAdNetworkConversionValueSchemaRequest', + 'UpdateSKAdNetworkConversionValueSchemaRequest', + 'ListSKAdNetworkConversionValueSchemasRequest', + 'ListSKAdNetworkConversionValueSchemasResponse', + 'GetGoogleSignalsSettingsRequest', + 'UpdateGoogleSignalsSettingsRequest', + 'CreateConversionEventRequest', + 'UpdateConversionEventRequest', + 'GetConversionEventRequest', + 'DeleteConversionEventRequest', + 'ListConversionEventsRequest', + 'ListConversionEventsResponse', + 'CreateKeyEventRequest', + 'UpdateKeyEventRequest', + 'GetKeyEventRequest', + 'DeleteKeyEventRequest', + 'ListKeyEventsRequest', + 'ListKeyEventsResponse', + 'GetDisplayVideo360AdvertiserLinkRequest', + 'ListDisplayVideo360AdvertiserLinksRequest', + 'ListDisplayVideo360AdvertiserLinksResponse', + 'CreateDisplayVideo360AdvertiserLinkRequest', + 'DeleteDisplayVideo360AdvertiserLinkRequest', + 'UpdateDisplayVideo360AdvertiserLinkRequest', + 'GetDisplayVideo360AdvertiserLinkProposalRequest', + 'ListDisplayVideo360AdvertiserLinkProposalsRequest', + 'ListDisplayVideo360AdvertiserLinkProposalsResponse', + 'CreateDisplayVideo360AdvertiserLinkProposalRequest', + 'DeleteDisplayVideo360AdvertiserLinkProposalRequest', + 'ApproveDisplayVideo360AdvertiserLinkProposalRequest', + 'ApproveDisplayVideo360AdvertiserLinkProposalResponse', + 'CancelDisplayVideo360AdvertiserLinkProposalRequest', + 'GetSearchAds360LinkRequest', + 'ListSearchAds360LinksRequest', + 'ListSearchAds360LinksResponse', + 'CreateSearchAds360LinkRequest', + 'DeleteSearchAds360LinkRequest', + 'UpdateSearchAds360LinkRequest', + 'CreateCustomDimensionRequest', + 'UpdateCustomDimensionRequest', + 'ListCustomDimensionsRequest', + 'ListCustomDimensionsResponse', + 'ArchiveCustomDimensionRequest', + 'GetCustomDimensionRequest', + 'CreateCustomMetricRequest', + 'UpdateCustomMetricRequest', + 'ListCustomMetricsRequest', + 'ListCustomMetricsResponse', + 'ArchiveCustomMetricRequest', + 'GetCustomMetricRequest', + 'CreateCalculatedMetricRequest', + 'UpdateCalculatedMetricRequest', + 'DeleteCalculatedMetricRequest', + 'ListCalculatedMetricsRequest', + 'ListCalculatedMetricsResponse', + 'GetCalculatedMetricRequest', + 'GetDataRetentionSettingsRequest', + 'UpdateDataRetentionSettingsRequest', + 'CreateDataStreamRequest', + 'DeleteDataStreamRequest', + 'UpdateDataStreamRequest', + 'ListDataStreamsRequest', + 'ListDataStreamsResponse', + 'GetDataStreamRequest', + 'GetAudienceRequest', + 'ListAudiencesRequest', + 'ListAudiencesResponse', + 'CreateAudienceRequest', + 'UpdateAudienceRequest', + 'ArchiveAudienceRequest', + 'GetAttributionSettingsRequest', + 'UpdateAttributionSettingsRequest', + 'GetAccessBindingRequest', + 'BatchGetAccessBindingsRequest', + 'BatchGetAccessBindingsResponse', + 'ListAccessBindingsRequest', + 'ListAccessBindingsResponse', + 'CreateAccessBindingRequest', + 'BatchCreateAccessBindingsRequest', + 'BatchCreateAccessBindingsResponse', + 'UpdateAccessBindingRequest', + 'BatchUpdateAccessBindingsRequest', + 'BatchUpdateAccessBindingsResponse', + 'DeleteAccessBindingRequest', + 'BatchDeleteAccessBindingsRequest', + 'CreateExpandedDataSetRequest', + 'UpdateExpandedDataSetRequest', + 'DeleteExpandedDataSetRequest', + 'GetExpandedDataSetRequest', + 'ListExpandedDataSetsRequest', + 'ListExpandedDataSetsResponse', + 'CreateChannelGroupRequest', + 'UpdateChannelGroupRequest', + 'DeleteChannelGroupRequest', + 'GetChannelGroupRequest', + 'ListChannelGroupsRequest', + 'ListChannelGroupsResponse', + 'SetAutomatedGa4ConfigurationOptOutRequest', + 'SetAutomatedGa4ConfigurationOptOutResponse', + 'FetchAutomatedGa4ConfigurationOptOutRequest', + 'FetchAutomatedGa4ConfigurationOptOutResponse', + 'CreateBigQueryLinkRequest', + 'GetBigQueryLinkRequest', + 'ListBigQueryLinksRequest', + 'ListBigQueryLinksResponse', + 'UpdateBigQueryLinkRequest', + 'DeleteBigQueryLinkRequest', + 'GetEnhancedMeasurementSettingsRequest', + 'UpdateEnhancedMeasurementSettingsRequest', + 'GetDataRedactionSettingsRequest', + 'UpdateDataRedactionSettingsRequest', + 'CreateConnectedSiteTagRequest', + 'CreateConnectedSiteTagResponse', + 'DeleteConnectedSiteTagRequest', + 'ListConnectedSiteTagsRequest', + 'ListConnectedSiteTagsResponse', + 'CreateAdSenseLinkRequest', + 'GetAdSenseLinkRequest', + 'DeleteAdSenseLinkRequest', + 'ListAdSenseLinksRequest', + 'ListAdSenseLinksResponse', + 'FetchConnectedGa4PropertyRequest', + 'FetchConnectedGa4PropertyResponse', + 'CreateEventCreateRuleRequest', + 'UpdateEventCreateRuleRequest', + 'DeleteEventCreateRuleRequest', + 'GetEventCreateRuleRequest', + 'ListEventCreateRulesRequest', + 'ListEventCreateRulesResponse', + 'CreateEventEditRuleRequest', + 'UpdateEventEditRuleRequest', + 'DeleteEventEditRuleRequest', + 'GetEventEditRuleRequest', + 'ListEventEditRulesRequest', + 'ListEventEditRulesResponse', + 'ReorderEventEditRulesRequest', + 'CreateRollupPropertyRequest', + 'CreateRollupPropertyResponse', + 'GetRollupPropertySourceLinkRequest', + 'ListRollupPropertySourceLinksRequest', + 'ListRollupPropertySourceLinksResponse', + 'CreateRollupPropertySourceLinkRequest', + 'DeleteRollupPropertySourceLinkRequest', + 'ProvisionSubpropertyRequest', + 'ProvisionSubpropertyResponse', + 'CreateSubpropertyEventFilterRequest', + 'GetSubpropertyEventFilterRequest', + 'ListSubpropertyEventFiltersRequest', + 'ListSubpropertyEventFiltersResponse', + 'UpdateSubpropertyEventFilterRequest', + 'DeleteSubpropertyEventFilterRequest', + }, +) + + +class RunAccessReportRequest(proto.Message): + r"""The request for a Data Access Record Report. + + Attributes: + entity (str): + The Data Access Report supports requesting at + the property level or account level. If + requested at the account level, Data Access + Reports include all access for all properties + under that account. + + To request at the property level, entity should + be for example 'properties/123' if "123" is your + GA4 property ID. To request at the account + level, entity should be for example + 'accounts/1234' if "1234" is your GA4 Account + ID. + dimensions (MutableSequence[google.analytics.admin_v1alpha.types.AccessDimension]): + The dimensions requested and displayed in the + response. Requests are allowed up to 9 + dimensions. + metrics (MutableSequence[google.analytics.admin_v1alpha.types.AccessMetric]): + The metrics requested and displayed in the + response. Requests are allowed up to 10 metrics. + date_ranges (MutableSequence[google.analytics.admin_v1alpha.types.AccessDateRange]): + Date ranges of access records to read. If + multiple date ranges are requested, each + response row will contain a zero based date + range index. If two date ranges overlap, the + access records for the overlapping days is + included in the response rows for both date + ranges. Requests are allowed up to 2 date + ranges. + dimension_filter (google.analytics.admin_v1alpha.types.AccessFilterExpression): + Dimension filters let you restrict report response to + specific dimension values which match the filter. For + example, filtering on access records of a single user. To + learn more, see `Fundamentals of Dimension + Filters `__ + for examples. Metrics cannot be used in this filter. + metric_filter (google.analytics.admin_v1alpha.types.AccessFilterExpression): + Metric filters allow you to restrict report + response to specific metric values which match + the filter. Metric filters are applied after + aggregating the report's rows, similar to SQL + having-clause. Dimensions cannot be used in this + filter. + offset (int): + The row count of the start row. The first row is counted as + row 0. If offset is unspecified, it is treated as 0. If + offset is zero, then this method will return the first page + of results with ``limit`` entries. + + To learn more about this pagination parameter, see + `Pagination `__. + limit (int): + The number of rows to return. If unspecified, 10,000 rows + are returned. The API returns a maximum of 100,000 rows per + request, no matter how many you ask for. ``limit`` must be + positive. + + The API may return fewer rows than the requested ``limit``, + if there aren't as many remaining rows as the ``limit``. For + instance, there are fewer than 300 possible values for the + dimension ``country``, so when reporting on only + ``country``, you can't get more than 300 rows, even if you + set ``limit`` to a higher value. + + To learn more about this pagination parameter, see + `Pagination `__. + time_zone (str): + This request's time zone if specified. If unspecified, the + property's time zone is used. The request's time zone is + used to interpret the start & end dates of the report. + + Formatted as strings from the IANA Time Zone database + (https://www.iana.org/time-zones); for example + "America/New_York" or "Asia/Tokyo". + order_bys (MutableSequence[google.analytics.admin_v1alpha.types.AccessOrderBy]): + Specifies how rows are ordered in the + response. + return_entity_quota (bool): + Toggles whether to return the current state of this + Analytics Property's quota. Quota is returned in + `AccessQuota <#AccessQuota>`__. For account-level requests, + this field must be false. + include_all_users (bool): + Optional. Determines whether to include users + who have never made an API call in the response. + If true, all users with access to the specified + property or account are included in the + response, regardless of whether they have made + an API call or not. If false, only the users who + have made an API call will be included. + expand_groups (bool): + Optional. Decides whether to return the users within user + groups. This field works only when include_all_users is set + to true. If true, it will return all users with access to + the specified property or account. If false, only the users + with direct access will be returned. + """ + + entity: str = proto.Field( + proto.STRING, + number=1, + ) + dimensions: MutableSequence[access_report.AccessDimension] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=access_report.AccessDimension, + ) + metrics: MutableSequence[access_report.AccessMetric] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=access_report.AccessMetric, + ) + date_ranges: MutableSequence[access_report.AccessDateRange] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=access_report.AccessDateRange, + ) + dimension_filter: access_report.AccessFilterExpression = proto.Field( + proto.MESSAGE, + number=5, + message=access_report.AccessFilterExpression, + ) + metric_filter: access_report.AccessFilterExpression = proto.Field( + proto.MESSAGE, + number=6, + message=access_report.AccessFilterExpression, + ) + offset: int = proto.Field( + proto.INT64, + number=7, + ) + limit: int = proto.Field( + proto.INT64, + number=8, + ) + time_zone: str = proto.Field( + proto.STRING, + number=9, + ) + order_bys: MutableSequence[access_report.AccessOrderBy] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=access_report.AccessOrderBy, + ) + return_entity_quota: bool = proto.Field( + proto.BOOL, + number=11, + ) + include_all_users: bool = proto.Field( + proto.BOOL, + number=12, + ) + expand_groups: bool = proto.Field( + proto.BOOL, + number=13, + ) + + +class RunAccessReportResponse(proto.Message): + r"""The customized Data Access Record Report response. + + Attributes: + dimension_headers (MutableSequence[google.analytics.admin_v1alpha.types.AccessDimensionHeader]): + The header for a column in the report that + corresponds to a specific dimension. The number + of DimensionHeaders and ordering of + DimensionHeaders matches the dimensions present + in rows. + metric_headers (MutableSequence[google.analytics.admin_v1alpha.types.AccessMetricHeader]): + The header for a column in the report that + corresponds to a specific metric. The number of + MetricHeaders and ordering of MetricHeaders + matches the metrics present in rows. + rows (MutableSequence[google.analytics.admin_v1alpha.types.AccessRow]): + Rows of dimension value combinations and + metric values in the report. + row_count (int): + The total number of rows in the query result. ``rowCount`` + is independent of the number of rows returned in the + response, the ``limit`` request parameter, and the + ``offset`` request parameter. For example if a query returns + 175 rows and includes ``limit`` of 50 in the API request, + the response will contain ``rowCount`` of 175 but only 50 + rows. + + To learn more about this pagination parameter, see + `Pagination `__. + quota (google.analytics.admin_v1alpha.types.AccessQuota): + The quota state for this Analytics property + including this request. This field doesn't work + with account-level requests. + """ + + dimension_headers: MutableSequence[access_report.AccessDimensionHeader] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=access_report.AccessDimensionHeader, + ) + metric_headers: MutableSequence[access_report.AccessMetricHeader] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=access_report.AccessMetricHeader, + ) + rows: MutableSequence[access_report.AccessRow] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=access_report.AccessRow, + ) + row_count: int = proto.Field( + proto.INT32, + number=4, + ) + quota: access_report.AccessQuota = proto.Field( + proto.MESSAGE, + number=5, + message=access_report.AccessQuota, + ) + + +class GetAccountRequest(proto.Message): + r"""Request message for GetAccount RPC. + + Attributes: + name (str): + Required. The name of the account to lookup. + Format: accounts/{account} + Example: "accounts/100". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAccountsRequest(proto.Message): + r"""Request message for ListAccounts RPC. + + Attributes: + page_size (int): + The maximum number of resources to return. + The service may return fewer than this value, + even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListAccounts`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListAccounts`` must match the call that provided the page + token. + show_deleted (bool): + Whether to include soft-deleted (ie: + "trashed") Accounts in the results. Accounts can + be inspected to determine whether they are + deleted or not. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ListAccountsResponse(proto.Message): + r"""Request message for ListAccounts RPC. + + Attributes: + accounts (MutableSequence[google.analytics.admin_v1alpha.types.Account]): + Results that were accessible to the caller. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + accounts: MutableSequence[resources.Account] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Account, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAccountRequest(proto.Message): + r"""Request message for DeleteAccount RPC. + + Attributes: + name (str): + Required. The name of the Account to + soft-delete. Format: accounts/{account} + Example: "accounts/100". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAccountRequest(proto.Message): + r"""Request message for UpdateAccount RPC. + + Attributes: + account (google.analytics.admin_v1alpha.types.Account): + Required. The account to update. The account's ``name`` + field is used to identify the account. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (for example, "field_to_update"). Omitted + fields will not be updated. To replace the entire entity, + use one path with the string "*" to match all fields. + """ + + account: resources.Account = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Account, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ProvisionAccountTicketRequest(proto.Message): + r"""Request message for ProvisionAccountTicket RPC. + + Attributes: + account (google.analytics.admin_v1alpha.types.Account): + The account to create. + redirect_uri (str): + Redirect URI where the user will be sent + after accepting Terms of Service. Must be + configured in Cloud Console as a Redirect URI. + """ + + account: resources.Account = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Account, + ) + redirect_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ProvisionAccountTicketResponse(proto.Message): + r"""Response message for ProvisionAccountTicket RPC. + + Attributes: + account_ticket_id (str): + The param to be passed in the ToS link. + """ + + account_ticket_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetPropertyRequest(proto.Message): + r"""Request message for GetProperty RPC. + + Attributes: + name (str): + Required. The name of the property to lookup. Format: + properties/{property_id} Example: "properties/1000". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPropertiesRequest(proto.Message): + r"""Request message for ListProperties RPC. + + Attributes: + filter (str): + Required. An expression for filtering the results of the + request. Fields eligible for filtering are: + ``parent:``\ (The resource name of the parent + account/property) or ``ancestor:``\ (The resource name of + the parent account) or ``firebase_project:``\ (The id or + number of the linked firebase project). Some examples of + filters: + + :: + + | Filter | Description | + |-----------------------------|-------------------------------------------| + | parent:accounts/123 | The account with account id: 123. | + | parent:properties/123 | The property with property id: 123. | + | ancestor:accounts/123 | The account with account id: 123. | + | firebase_project:project-id | The firebase project with id: project-id. | + | firebase_project:123 | The firebase project with number: 123. | + page_size (int): + The maximum number of resources to return. + The service may return fewer than this value, + even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListProperties`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListProperties`` must match the call that provided the + page token. + show_deleted (bool): + Whether to include soft-deleted (ie: + "trashed") Properties in the results. Properties + can be inspected to determine whether they are + deleted or not. + """ + + filter: 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, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListPropertiesResponse(proto.Message): + r"""Response message for ListProperties RPC. + + Attributes: + properties (MutableSequence[google.analytics.admin_v1alpha.types.Property]): + Results that matched the filter criteria and + were accessible to the caller. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + properties: MutableSequence[resources.Property] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Property, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdatePropertyRequest(proto.Message): + r"""Request message for UpdateProperty RPC. + + Attributes: + property (google.analytics.admin_v1alpha.types.Property): + Required. The property to update. The property's ``name`` + field is used to identify the property to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + property: resources.Property = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Property, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CreatePropertyRequest(proto.Message): + r"""Request message for CreateProperty RPC. + + Attributes: + property (google.analytics.admin_v1alpha.types.Property): + Required. The property to create. + Note: the supplied property must specify its + parent. + """ + + property: resources.Property = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Property, + ) + + +class DeletePropertyRequest(proto.Message): + r"""Request message for DeleteProperty RPC. + + Attributes: + name (str): + Required. The name of the Property to soft-delete. Format: + properties/{property_id} Example: "properties/1000". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateFirebaseLinkRequest(proto.Message): + r"""Request message for CreateFirebaseLink RPC + + Attributes: + parent (str): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + firebase_link (google.analytics.admin_v1alpha.types.FirebaseLink): + Required. The Firebase link to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + firebase_link: resources.FirebaseLink = proto.Field( + proto.MESSAGE, + number=2, + message=resources.FirebaseLink, + ) + + +class DeleteFirebaseLinkRequest(proto.Message): + r"""Request message for DeleteFirebaseLink RPC + + Attributes: + name (str): + Required. Format: + properties/{property_id}/firebaseLinks/{firebase_link_id} + + Example: ``properties/1234/firebaseLinks/5678`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFirebaseLinksRequest(proto.Message): + r"""Request message for ListFirebaseLinks RPC + + Attributes: + parent (str): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + page_size (int): + The maximum number of resources to return. + The service may return fewer than this value, + even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListFirebaseLinks`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListFirebaseLinks`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListFirebaseLinksResponse(proto.Message): + r"""Response message for ListFirebaseLinks RPC + + Attributes: + firebase_links (MutableSequence[google.analytics.admin_v1alpha.types.FirebaseLink]): + List of FirebaseLinks. This will have at most + one value. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. Currently, Google Analytics supports only one + FirebaseLink per property, so this will never be populated. + """ + + @property + def raw_page(self): + return self + + firebase_links: MutableSequence[resources.FirebaseLink] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.FirebaseLink, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetGlobalSiteTagRequest(proto.Message): + r"""Request message for GetGlobalSiteTag RPC. + + Attributes: + name (str): + Required. The name of the site tag to lookup. Note that site + tags are singletons and do not have unique IDs. Format: + properties/{property_id}/dataStreams/{stream_id}/globalSiteTag + + Example: ``properties/123/dataStreams/456/globalSiteTag`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateGoogleAdsLinkRequest(proto.Message): + r"""Request message for CreateGoogleAdsLink RPC + + Attributes: + parent (str): + Required. Example format: properties/1234 + google_ads_link (google.analytics.admin_v1alpha.types.GoogleAdsLink): + Required. The GoogleAdsLink to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + google_ads_link: resources.GoogleAdsLink = proto.Field( + proto.MESSAGE, + number=2, + message=resources.GoogleAdsLink, + ) + + +class UpdateGoogleAdsLinkRequest(proto.Message): + r"""Request message for UpdateGoogleAdsLink RPC + + Attributes: + google_ads_link (google.analytics.admin_v1alpha.types.GoogleAdsLink): + The GoogleAdsLink to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + google_ads_link: resources.GoogleAdsLink = proto.Field( + proto.MESSAGE, + number=1, + message=resources.GoogleAdsLink, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteGoogleAdsLinkRequest(proto.Message): + r"""Request message for DeleteGoogleAdsLink RPC. + + Attributes: + name (str): + Required. Example format: + properties/1234/googleAdsLinks/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListGoogleAdsLinksRequest(proto.Message): + r"""Request message for ListGoogleAdsLinks RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous + ``ListGoogleAdsLinks`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListGoogleAdsLinks`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListGoogleAdsLinksResponse(proto.Message): + r"""Response message for ListGoogleAdsLinks RPC. + + Attributes: + google_ads_links (MutableSequence[google.analytics.admin_v1alpha.types.GoogleAdsLink]): + List of GoogleAdsLinks. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + google_ads_links: MutableSequence[resources.GoogleAdsLink] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.GoogleAdsLink, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetDataSharingSettingsRequest(proto.Message): + r"""Request message for GetDataSharingSettings RPC. + + Attributes: + name (str): + Required. The name of the settings to lookup. Format: + accounts/{account}/dataSharingSettings + + Example: ``accounts/1000/dataSharingSettings`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAccountSummariesRequest(proto.Message): + r"""Request message for ListAccountSummaries RPC. + + Attributes: + page_size (int): + The maximum number of AccountSummary + resources to return. The service may return + fewer than this value, even if there are + additional pages. If unspecified, at most 50 + resources will be returned. The maximum value is + 200; (higher values will be coerced to the + maximum) + page_token (str): + A page token, received from a previous + ``ListAccountSummaries`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListAccountSummaries`` must match the call + that provided the page token. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAccountSummariesResponse(proto.Message): + r"""Response message for ListAccountSummaries RPC. + + Attributes: + account_summaries (MutableSequence[google.analytics.admin_v1alpha.types.AccountSummary]): + Account summaries of all accounts the caller + has access to. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + account_summaries: MutableSequence[resources.AccountSummary] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.AccountSummary, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AcknowledgeUserDataCollectionRequest(proto.Message): + r"""Request message for AcknowledgeUserDataCollection RPC. + + Attributes: + property (str): + Required. The property for which to + acknowledge user data collection. + acknowledgement (str): + Required. An acknowledgement that the caller + of this method understands the terms of user + data collection. + + This field must contain the exact value: + + "I acknowledge that I have the necessary privacy + disclosures and rights from my end users for the + collection and processing of their data, + including the association of such data with the + visitation information Google Analytics collects + from my site and/or app property.". + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + acknowledgement: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AcknowledgeUserDataCollectionResponse(proto.Message): + r"""Response message for AcknowledgeUserDataCollection RPC. + """ + + +class SearchChangeHistoryEventsRequest(proto.Message): + r"""Request message for SearchChangeHistoryEvents RPC. + + Attributes: + account (str): + Required. The account resource for which to return change + history resources. Format: accounts/{account} + + Example: ``accounts/100`` + property (str): + Optional. Resource name for a child property. If set, only + return changes made to this property or its child resources. + Format: properties/{propertyId} + + Example: ``properties/100`` + resource_type (MutableSequence[google.analytics.admin_v1alpha.types.ChangeHistoryResourceType]): + Optional. If set, only return changes if they + are for a resource that matches at least one of + these types. + action (MutableSequence[google.analytics.admin_v1alpha.types.ActionType]): + Optional. If set, only return changes that + match one or more of these types of actions. + actor_email (MutableSequence[str]): + Optional. If set, only return changes if they + are made by a user in this list. + earliest_change_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. If set, only return changes made + after this time (inclusive). + latest_change_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. If set, only return changes made + before this time (inclusive). + page_size (int): + Optional. The maximum number of + ChangeHistoryEvent items to return. The service + may return fewer than this value, even if there + are additional pages. If unspecified, at most 50 + items will be returned. The maximum value is 200 + (higher values will be coerced to the maximum). + page_token (str): + Optional. A page token, received from a previous + ``SearchChangeHistoryEvents`` call. Provide this to retrieve + the subsequent page. When paginating, all other parameters + provided to ``SearchChangeHistoryEvents`` must match the + call that provided the page token. + """ + + account: str = proto.Field( + proto.STRING, + number=1, + ) + property: str = proto.Field( + proto.STRING, + number=2, + ) + resource_type: MutableSequence[resources.ChangeHistoryResourceType] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=resources.ChangeHistoryResourceType, + ) + action: MutableSequence[resources.ActionType] = proto.RepeatedField( + proto.ENUM, + number=4, + enum=resources.ActionType, + ) + actor_email: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + earliest_change_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + latest_change_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + page_token: str = proto.Field( + proto.STRING, + number=9, + ) + + +class SearchChangeHistoryEventsResponse(proto.Message): + r"""Response message for SearchAccounts RPC. + + Attributes: + change_history_events (MutableSequence[google.analytics.admin_v1alpha.types.ChangeHistoryEvent]): + Results that were accessible to the caller. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + change_history_events: MutableSequence[resources.ChangeHistoryEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.ChangeHistoryEvent, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetMeasurementProtocolSecretRequest(proto.Message): + r"""Request message for GetMeasurementProtocolSecret RPC. + + Attributes: + name (str): + Required. The name of the measurement + protocol secret to lookup. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMeasurementProtocolSecretRequest(proto.Message): + r"""Request message for CreateMeasurementProtocolSecret RPC + + Attributes: + parent (str): + Required. The parent resource where this + secret will be created. Format: + properties/{property}/dataStreams/{dataStream} + measurement_protocol_secret (google.analytics.admin_v1alpha.types.MeasurementProtocolSecret): + Required. The measurement protocol secret to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + measurement_protocol_secret: resources.MeasurementProtocolSecret = proto.Field( + proto.MESSAGE, + number=2, + message=resources.MeasurementProtocolSecret, + ) + + +class DeleteMeasurementProtocolSecretRequest(proto.Message): + r"""Request message for DeleteMeasurementProtocolSecret RPC + + Attributes: + name (str): + Required. The name of the + MeasurementProtocolSecret to delete. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateMeasurementProtocolSecretRequest(proto.Message): + r"""Request message for UpdateMeasurementProtocolSecret RPC + + Attributes: + measurement_protocol_secret (google.analytics.admin_v1alpha.types.MeasurementProtocolSecret): + Required. The measurement protocol secret to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. + Omitted fields will not be updated. + """ + + measurement_protocol_secret: resources.MeasurementProtocolSecret = proto.Field( + proto.MESSAGE, + number=1, + message=resources.MeasurementProtocolSecret, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListMeasurementProtocolSecretsRequest(proto.Message): + r"""Request message for ListMeasurementProtocolSecret RPC + + Attributes: + parent (str): + Required. The resource name of the parent + stream. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + page_size (int): + The maximum number of resources to return. + If unspecified, at most 10 resources will be + returned. The maximum value is 10. Higher values + will be coerced to the maximum. + page_token (str): + A page token, received from a previous + ``ListMeasurementProtocolSecrets`` call. Provide this to + retrieve the subsequent page. When paginating, all other + parameters provided to ``ListMeasurementProtocolSecrets`` + must match the call that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMeasurementProtocolSecretsResponse(proto.Message): + r"""Response message for ListMeasurementProtocolSecret RPC + + Attributes: + measurement_protocol_secrets (MutableSequence[google.analytics.admin_v1alpha.types.MeasurementProtocolSecret]): + A list of secrets for the parent stream + specified in the request. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + measurement_protocol_secrets: MutableSequence[resources.MeasurementProtocolSecret] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.MeasurementProtocolSecret, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSKAdNetworkConversionValueSchemaRequest(proto.Message): + r"""Request message for GetSKAdNetworkConversionValueSchema RPC. + + Attributes: + name (str): + Required. The resource name of SKAdNetwork conversion value + schema to look up. Format: + properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateSKAdNetworkConversionValueSchemaRequest(proto.Message): + r"""Request message for CreateSKAdNetworkConversionValueSchema + RPC. + + Attributes: + parent (str): + Required. The parent resource where this + schema will be created. Format: + properties/{property}/dataStreams/{dataStream} + skadnetwork_conversion_value_schema (google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema): + Required. SKAdNetwork conversion value schema + to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + skadnetwork_conversion_value_schema: resources.SKAdNetworkConversionValueSchema = proto.Field( + proto.MESSAGE, + number=2, + message=resources.SKAdNetworkConversionValueSchema, + ) + + +class DeleteSKAdNetworkConversionValueSchemaRequest(proto.Message): + r"""Request message for DeleteSKAdNetworkConversionValueSchema + RPC. + + Attributes: + name (str): + Required. The name of the SKAdNetworkConversionValueSchema + to delete. Format: + properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSKAdNetworkConversionValueSchemaRequest(proto.Message): + r"""Request message for UpdateSKAdNetworkConversionValueSchema + RPC. + + Attributes: + skadnetwork_conversion_value_schema (google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema): + Required. SKAdNetwork conversion value schema + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. + Omitted fields will not be updated. + """ + + skadnetwork_conversion_value_schema: resources.SKAdNetworkConversionValueSchema = proto.Field( + proto.MESSAGE, + number=1, + message=resources.SKAdNetworkConversionValueSchema, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListSKAdNetworkConversionValueSchemasRequest(proto.Message): + r"""Request message for ListSKAdNetworkConversionValueSchemas RPC + + Attributes: + parent (str): + Required. The DataStream resource to list schemas for. + Format: properties/{property_id}/dataStreams/{dataStream} + Example: properties/1234/dataStreams/5678 + page_size (int): + The maximum number of resources to return. + The service may return fewer than this value, + even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous + ``ListSKAdNetworkConversionValueSchemas`` call. Provide this + to retrieve the subsequent page. When paginating, all other + parameters provided to + ``ListSKAdNetworkConversionValueSchema`` must match the call + that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSKAdNetworkConversionValueSchemasResponse(proto.Message): + r"""Response message for ListSKAdNetworkConversionValueSchemas + RPC + + Attributes: + skadnetwork_conversion_value_schemas (MutableSequence[google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema]): + List of SKAdNetworkConversionValueSchemas. + This will have at most one value. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. Currently, Google Analytics supports only one + SKAdNetworkConversionValueSchema per dataStream, so this + will never be populated. + """ + + @property + def raw_page(self): + return self + + skadnetwork_conversion_value_schemas: MutableSequence[resources.SKAdNetworkConversionValueSchema] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.SKAdNetworkConversionValueSchema, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetGoogleSignalsSettingsRequest(proto.Message): + r"""Request message for GetGoogleSignalsSettings RPC + + Attributes: + name (str): + Required. The name of the google signals + settings to retrieve. Format: + properties/{property}/googleSignalsSettings + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateGoogleSignalsSettingsRequest(proto.Message): + r"""Request message for UpdateGoogleSignalsSettings RPC + + Attributes: + google_signals_settings (google.analytics.admin_v1alpha.types.GoogleSignalsSettings): + Required. The settings to update. The ``name`` field is used + to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + google_signals_settings: resources.GoogleSignalsSettings = proto.Field( + proto.MESSAGE, + number=1, + message=resources.GoogleSignalsSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CreateConversionEventRequest(proto.Message): + r"""Request message for CreateConversionEvent RPC + + Attributes: + conversion_event (google.analytics.admin_v1alpha.types.ConversionEvent): + Required. The conversion event to create. + parent (str): + Required. The resource name of the parent + property where this conversion event will be + created. Format: properties/123 + """ + + conversion_event: resources.ConversionEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.ConversionEvent, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateConversionEventRequest(proto.Message): + r"""Request message for UpdateConversionEvent RPC + + Attributes: + conversion_event (google.analytics.admin_v1alpha.types.ConversionEvent): + Required. The conversion event to update. The ``name`` field + is used to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + conversion_event: resources.ConversionEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.ConversionEvent, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetConversionEventRequest(proto.Message): + r"""Request message for GetConversionEvent RPC + + Attributes: + name (str): + Required. The resource name of the conversion event to + retrieve. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteConversionEventRequest(proto.Message): + r"""Request message for DeleteConversionEvent RPC + + Attributes: + name (str): + Required. The resource name of the conversion event to + delete. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListConversionEventsRequest(proto.Message): + r"""Request message for ListConversionEvents RPC + + Attributes: + parent (str): + Required. The resource name of the parent + property. Example: 'properties/123' + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous + ``ListConversionEvents`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListConversionEvents`` must match the call + that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListConversionEventsResponse(proto.Message): + r"""Response message for ListConversionEvents RPC. + + Attributes: + conversion_events (MutableSequence[google.analytics.admin_v1alpha.types.ConversionEvent]): + The requested conversion events + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + conversion_events: MutableSequence[resources.ConversionEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.ConversionEvent, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateKeyEventRequest(proto.Message): + r"""Request message for CreateKeyEvent RPC + + Attributes: + key_event (google.analytics.admin_v1alpha.types.KeyEvent): + Required. The Key Event to create. + parent (str): + Required. The resource name of the parent + property where this Key Event will be created. + Format: properties/123 + """ + + key_event: resources.KeyEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.KeyEvent, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateKeyEventRequest(proto.Message): + r"""Request message for UpdateKeyEvent RPC + + Attributes: + key_event (google.analytics.admin_v1alpha.types.KeyEvent): + Required. The Key Event to update. The ``name`` field is + used to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + key_event: resources.KeyEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.KeyEvent, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetKeyEventRequest(proto.Message): + r"""Request message for GetKeyEvent RPC + + Attributes: + name (str): + Required. The resource name of the Key Event to retrieve. + Format: properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteKeyEventRequest(proto.Message): + r"""Request message for DeleteKeyEvent RPC + + Attributes: + name (str): + Required. The resource name of the Key Event to delete. + Format: properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListKeyEventsRequest(proto.Message): + r"""Request message for ListKeyEvents RPC + + Attributes: + parent (str): + Required. The resource name of the parent + property. Example: 'properties/123' + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListKeyEvents`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListKeyEvents`` must match the call that provided the page + token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListKeyEventsResponse(proto.Message): + r"""Response message for ListKeyEvents RPC. + + Attributes: + key_events (MutableSequence[google.analytics.admin_v1alpha.types.KeyEvent]): + The requested Key Events + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + key_events: MutableSequence[resources.KeyEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.KeyEvent, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetDisplayVideo360AdvertiserLinkRequest(proto.Message): + r"""Request message for GetDisplayVideo360AdvertiserLink RPC. + + Attributes: + name (str): + Required. The name of the + DisplayVideo360AdvertiserLink to get. Example + format: + properties/1234/displayVideo360AdvertiserLink/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDisplayVideo360AdvertiserLinksRequest(proto.Message): + r"""Request message for ListDisplayVideo360AdvertiserLinks RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous + ``ListDisplayVideo360AdvertiserLinks`` call. Provide this to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListDisplayVideo360AdvertiserLinks`` must match the call + that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDisplayVideo360AdvertiserLinksResponse(proto.Message): + r"""Response message for ListDisplayVideo360AdvertiserLinks RPC. + + Attributes: + display_video_360_advertiser_links (MutableSequence[google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink]): + List of DisplayVideo360AdvertiserLinks. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + display_video_360_advertiser_links: MutableSequence[resources.DisplayVideo360AdvertiserLink] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.DisplayVideo360AdvertiserLink, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDisplayVideo360AdvertiserLinkRequest(proto.Message): + r"""Request message for CreateDisplayVideo360AdvertiserLink RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): + Required. The DisplayVideo360AdvertiserLink + to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + display_video_360_advertiser_link: resources.DisplayVideo360AdvertiserLink = proto.Field( + proto.MESSAGE, + number=2, + message=resources.DisplayVideo360AdvertiserLink, + ) + + +class DeleteDisplayVideo360AdvertiserLinkRequest(proto.Message): + r"""Request message for DeleteDisplayVideo360AdvertiserLink RPC. + + Attributes: + name (str): + Required. The name of the + DisplayVideo360AdvertiserLink to delete. Example + format: + properties/1234/displayVideo360AdvertiserLinks/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDisplayVideo360AdvertiserLinkRequest(proto.Message): + r"""Request message for UpdateDisplayVideo360AdvertiserLink RPC. + + Attributes: + display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): + The DisplayVideo360AdvertiserLink to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + display_video_360_advertiser_link: resources.DisplayVideo360AdvertiserLink = proto.Field( + proto.MESSAGE, + number=1, + message=resources.DisplayVideo360AdvertiserLink, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetDisplayVideo360AdvertiserLinkProposalRequest(proto.Message): + r"""Request message for GetDisplayVideo360AdvertiserLinkProposal + RPC. + + Attributes: + name (str): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to get. + Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListDisplayVideo360AdvertiserLinkProposalsRequest(proto.Message): + r"""Request message for + ListDisplayVideo360AdvertiserLinkProposals RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous + ``ListDisplayVideo360AdvertiserLinkProposals`` call. Provide + this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListDisplayVideo360AdvertiserLinkProposals`` must match + the call that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDisplayVideo360AdvertiserLinkProposalsResponse(proto.Message): + r"""Response message for + ListDisplayVideo360AdvertiserLinkProposals RPC. + + Attributes: + display_video_360_advertiser_link_proposals (MutableSequence[google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal]): + List of + DisplayVideo360AdvertiserLinkProposals. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + display_video_360_advertiser_link_proposals: MutableSequence[resources.DisplayVideo360AdvertiserLinkProposal] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.DisplayVideo360AdvertiserLinkProposal, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateDisplayVideo360AdvertiserLinkProposalRequest(proto.Message): + r"""Request message for + CreateDisplayVideo360AdvertiserLinkProposal RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + display_video_360_advertiser_link_proposal (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal): + Required. The + DisplayVideo360AdvertiserLinkProposal to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + display_video_360_advertiser_link_proposal: resources.DisplayVideo360AdvertiserLinkProposal = proto.Field( + proto.MESSAGE, + number=2, + message=resources.DisplayVideo360AdvertiserLinkProposal, + ) + + +class DeleteDisplayVideo360AdvertiserLinkProposalRequest(proto.Message): + r"""Request message for + DeleteDisplayVideo360AdvertiserLinkProposal RPC. + + Attributes: + name (str): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to delete. + Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ApproveDisplayVideo360AdvertiserLinkProposalRequest(proto.Message): + r"""Request message for + ApproveDisplayVideo360AdvertiserLinkProposal RPC. + + Attributes: + name (str): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to + approve. Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ApproveDisplayVideo360AdvertiserLinkProposalResponse(proto.Message): + r"""Response message for + ApproveDisplayVideo360AdvertiserLinkProposal RPC. + + Attributes: + display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): + The DisplayVideo360AdvertiserLink created as + a result of approving the proposal. + """ + + display_video_360_advertiser_link: resources.DisplayVideo360AdvertiserLink = proto.Field( + proto.MESSAGE, + number=1, + message=resources.DisplayVideo360AdvertiserLink, + ) + + +class CancelDisplayVideo360AdvertiserLinkProposalRequest(proto.Message): + r"""Request message for + CancelDisplayVideo360AdvertiserLinkProposal RPC. + + Attributes: + name (str): + Required. The name of the + DisplayVideo360AdvertiserLinkProposal to cancel. + Example format: + properties/1234/displayVideo360AdvertiserLinkProposals/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetSearchAds360LinkRequest(proto.Message): + r"""Request message for GetSearchAds360Link RPC. + + Attributes: + name (str): + Required. The name of the SearchAds360Link to + get. Example format: + properties/1234/SearchAds360Link/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSearchAds360LinksRequest(proto.Message): + r"""Request message for ListSearchAds360Links RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous + ``ListSearchAds360Links`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListSearchAds360Links`` must match the call that provided + the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSearchAds360LinksResponse(proto.Message): + r"""Response message for ListSearchAds360Links RPC. + + Attributes: + search_ads_360_links (MutableSequence[google.analytics.admin_v1alpha.types.SearchAds360Link]): + List of SearchAds360Links. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + search_ads_360_links: MutableSequence[resources.SearchAds360Link] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.SearchAds360Link, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateSearchAds360LinkRequest(proto.Message): + r"""Request message for CreateSearchAds360Link RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + search_ads_360_link (google.analytics.admin_v1alpha.types.SearchAds360Link): + Required. The SearchAds360Link to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + search_ads_360_link: resources.SearchAds360Link = proto.Field( + proto.MESSAGE, + number=2, + message=resources.SearchAds360Link, + ) + + +class DeleteSearchAds360LinkRequest(proto.Message): + r"""Request message for DeleteSearchAds360Link RPC. + + Attributes: + name (str): + Required. The name of the SearchAds360Link to + delete. Example format: + properties/1234/SearchAds360Links/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSearchAds360LinkRequest(proto.Message): + r"""Request message for UpdateSearchAds360Link RPC. + + Attributes: + search_ads_360_link (google.analytics.admin_v1alpha.types.SearchAds360Link): + The SearchAds360Link to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + search_ads_360_link: resources.SearchAds360Link = proto.Field( + proto.MESSAGE, + number=1, + message=resources.SearchAds360Link, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CreateCustomDimensionRequest(proto.Message): + r"""Request message for CreateCustomDimension RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + custom_dimension (google.analytics.admin_v1alpha.types.CustomDimension): + Required. The CustomDimension to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + custom_dimension: resources.CustomDimension = proto.Field( + proto.MESSAGE, + number=2, + message=resources.CustomDimension, + ) + + +class UpdateCustomDimensionRequest(proto.Message): + r"""Request message for UpdateCustomDimension RPC. + + Attributes: + custom_dimension (google.analytics.admin_v1alpha.types.CustomDimension): + The CustomDimension to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + custom_dimension: resources.CustomDimension = proto.Field( + proto.MESSAGE, + number=1, + message=resources.CustomDimension, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListCustomDimensionsRequest(proto.Message): + r"""Request message for ListCustomDimensions RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous + ``ListCustomDimensions`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListCustomDimensions`` must match the call that provided + the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCustomDimensionsResponse(proto.Message): + r"""Response message for ListCustomDimensions RPC. + + Attributes: + custom_dimensions (MutableSequence[google.analytics.admin_v1alpha.types.CustomDimension]): + List of CustomDimensions. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + custom_dimensions: MutableSequence[resources.CustomDimension] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CustomDimension, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ArchiveCustomDimensionRequest(proto.Message): + r"""Request message for ArchiveCustomDimension RPC. + + Attributes: + name (str): + Required. The name of the CustomDimension to + archive. Example format: + properties/1234/customDimensions/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetCustomDimensionRequest(proto.Message): + r"""Request message for GetCustomDimension RPC. + + Attributes: + name (str): + Required. The name of the CustomDimension to + get. Example format: + properties/1234/customDimensions/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateCustomMetricRequest(proto.Message): + r"""Request message for CreateCustomMetric RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + custom_metric (google.analytics.admin_v1alpha.types.CustomMetric): + Required. The CustomMetric to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + custom_metric: resources.CustomMetric = proto.Field( + proto.MESSAGE, + number=2, + message=resources.CustomMetric, + ) + + +class UpdateCustomMetricRequest(proto.Message): + r"""Request message for UpdateCustomMetric RPC. + + Attributes: + custom_metric (google.analytics.admin_v1alpha.types.CustomMetric): + The CustomMetric to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + custom_metric: resources.CustomMetric = proto.Field( + proto.MESSAGE, + number=1, + message=resources.CustomMetric, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListCustomMetricsRequest(proto.Message): + r"""Request message for ListCustomMetrics RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous ``ListCustomMetrics`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListCustomMetrics`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCustomMetricsResponse(proto.Message): + r"""Response message for ListCustomMetrics RPC. + + Attributes: + custom_metrics (MutableSequence[google.analytics.admin_v1alpha.types.CustomMetric]): + List of CustomMetrics. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + custom_metrics: MutableSequence[resources.CustomMetric] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CustomMetric, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ArchiveCustomMetricRequest(proto.Message): + r"""Request message for ArchiveCustomMetric RPC. + + Attributes: + name (str): + Required. The name of the CustomMetric to + archive. Example format: + properties/1234/customMetrics/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetCustomMetricRequest(proto.Message): + r"""Request message for GetCustomMetric RPC. + + Attributes: + name (str): + Required. The name of the CustomMetric to + get. Example format: + properties/1234/customMetrics/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateCalculatedMetricRequest(proto.Message): + r"""Request message for CreateCalculatedMetric RPC. + + Attributes: + parent (str): + Required. Format: properties/{property_id} Example: + properties/1234 + calculated_metric_id (str): + Required. The ID to use for the calculated metric which will + become the final component of the calculated metric's + resource name. + + This value should be 1-80 characters and valid characters + are /[a-zA-Z0-9_]/, no spaces allowed. calculated_metric_id + must be unique between all calculated metrics under a + property. The calculated_metric_id is used when referencing + this calculated metric from external APIs, for example, + "calcMetric:{calculated_metric_id}". + calculated_metric (google.analytics.admin_v1alpha.types.CalculatedMetric): + Required. The CalculatedMetric to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + calculated_metric_id: str = proto.Field( + proto.STRING, + number=2, + ) + calculated_metric: resources.CalculatedMetric = proto.Field( + proto.MESSAGE, + number=3, + message=resources.CalculatedMetric, + ) + + +class UpdateCalculatedMetricRequest(proto.Message): + r"""Request message for UpdateCalculatedMetric RPC. + + Attributes: + calculated_metric (google.analytics.admin_v1alpha.types.CalculatedMetric): + Required. The CalculatedMetric to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + calculated_metric: resources.CalculatedMetric = proto.Field( + proto.MESSAGE, + number=1, + message=resources.CalculatedMetric, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteCalculatedMetricRequest(proto.Message): + r"""Request message for DeleteCalculatedMetric RPC. + + Attributes: + name (str): + Required. The name of the CalculatedMetric to delete. + Format: + properties/{property_id}/calculatedMetrics/{calculated_metric_id} + Example: properties/1234/calculatedMetrics/Metric01 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListCalculatedMetricsRequest(proto.Message): + r"""Request message for ListCalculatedMetrics RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + Optional. The maximum number of resources to + return. If unspecified, at most 50 resources + will be returned. The maximum value is 200 + (higher values will be coerced to the maximum). + page_token (str): + Optional. A page token, received from a previous + ``ListCalculatedMetrics`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListCalculatedMetrics`` must match the call that provided + the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCalculatedMetricsResponse(proto.Message): + r"""Response message for ListCalculatedMetrics RPC. + + Attributes: + calculated_metrics (MutableSequence[google.analytics.admin_v1alpha.types.CalculatedMetric]): + List of CalculatedMetrics. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + calculated_metrics: MutableSequence[resources.CalculatedMetric] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CalculatedMetric, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetCalculatedMetricRequest(proto.Message): + r"""Request message for GetCalculatedMetric RPC. + + Attributes: + name (str): + Required. The name of the CalculatedMetric to get. Format: + properties/{property_id}/calculatedMetrics/{calculated_metric_id} + Example: properties/1234/calculatedMetrics/Metric01 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDataRetentionSettingsRequest(proto.Message): + r"""Request message for GetDataRetentionSettings RPC. + + Attributes: + name (str): + Required. The name of the settings to lookup. + Format: + + properties/{property}/dataRetentionSettings + Example: "properties/1000/dataRetentionSettings". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDataRetentionSettingsRequest(proto.Message): + r"""Request message for UpdateDataRetentionSettings RPC. + + Attributes: + data_retention_settings (google.analytics.admin_v1alpha.types.DataRetentionSettings): + Required. The settings to update. The ``name`` field is used + to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + data_retention_settings: resources.DataRetentionSettings = proto.Field( + proto.MESSAGE, + number=1, + message=resources.DataRetentionSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CreateDataStreamRequest(proto.Message): + r"""Request message for CreateDataStream RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + data_stream (google.analytics.admin_v1alpha.types.DataStream): + Required. The DataStream to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_stream: resources.DataStream = proto.Field( + proto.MESSAGE, + number=2, + message=resources.DataStream, + ) + + +class DeleteDataStreamRequest(proto.Message): + r"""Request message for DeleteDataStream RPC. + + Attributes: + name (str): + Required. The name of the DataStream to + delete. Example format: + properties/1234/dataStreams/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDataStreamRequest(proto.Message): + r"""Request message for UpdateDataStream RPC. + + Attributes: + data_stream (google.analytics.admin_v1alpha.types.DataStream): + The DataStream to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + data_stream: resources.DataStream = proto.Field( + proto.MESSAGE, + number=1, + message=resources.DataStream, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListDataStreamsRequest(proto.Message): + r"""Request message for ListDataStreams RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous ``ListDataStreams`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListDataStreams`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDataStreamsResponse(proto.Message): + r"""Response message for ListDataStreams RPC. + + Attributes: + data_streams (MutableSequence[google.analytics.admin_v1alpha.types.DataStream]): + List of DataStreams. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + data_streams: MutableSequence[resources.DataStream] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.DataStream, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetDataStreamRequest(proto.Message): + r"""Request message for GetDataStream RPC. + + Attributes: + name (str): + Required. The name of the DataStream to get. + Example format: properties/1234/dataStreams/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetAudienceRequest(proto.Message): + r"""Request message for GetAudience RPC. + + Attributes: + name (str): + Required. The name of the Audience to get. + Example format: properties/1234/audiences/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAudiencesRequest(proto.Message): + r"""Request message for ListAudiences RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous ``ListAudiences`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListAudiences`` must match the call that provided the page + token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAudiencesResponse(proto.Message): + r"""Response message for ListAudiences RPC. + + Attributes: + audiences (MutableSequence[google.analytics.admin_v1alpha.types.Audience]): + List of Audiences. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + audiences: MutableSequence[gaa_audience.Audience] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gaa_audience.Audience, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateAudienceRequest(proto.Message): + r"""Request message for CreateAudience RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + audience (google.analytics.admin_v1alpha.types.Audience): + Required. The audience to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + audience: gaa_audience.Audience = proto.Field( + proto.MESSAGE, + number=2, + message=gaa_audience.Audience, + ) + + +class UpdateAudienceRequest(proto.Message): + r"""Request message for UpdateAudience RPC. + + Attributes: + audience (google.analytics.admin_v1alpha.types.Audience): + Required. The audience to update. The audience's ``name`` + field is used to identify the audience to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + audience: gaa_audience.Audience = proto.Field( + proto.MESSAGE, + number=1, + message=gaa_audience.Audience, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ArchiveAudienceRequest(proto.Message): + r"""Request message for ArchiveAudience RPC. + + Attributes: + name (str): + Required. Example format: + properties/1234/audiences/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetAttributionSettingsRequest(proto.Message): + r"""Request message for GetAttributionSettings RPC. + + Attributes: + name (str): + Required. The name of the attribution + settings to retrieve. Format: + properties/{property}/attributionSettings + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAttributionSettingsRequest(proto.Message): + r"""Request message for UpdateAttributionSettings RPC + + Attributes: + attribution_settings (google.analytics.admin_v1alpha.types.AttributionSettings): + Required. The attribution settings to update. The ``name`` + field is used to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + attribution_settings: resources.AttributionSettings = proto.Field( + proto.MESSAGE, + number=1, + message=resources.AttributionSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetAccessBindingRequest(proto.Message): + r"""Request message for GetAccessBinding RPC. + + Attributes: + name (str): + Required. The name of the access binding to + retrieve. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchGetAccessBindingsRequest(proto.Message): + r"""Request message for BatchGetAccessBindings RPC. + + Attributes: + parent (str): + Required. The account or property that owns + the access bindings. The parent of all provided + values for the 'names' field must match this + field. Formats: + + - accounts/{account} + - properties/{property} + names (MutableSequence[str]): + Required. The names of the access bindings to + retrieve. A maximum of 1000 access bindings can + be retrieved in a batch. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchGetAccessBindingsResponse(proto.Message): + r"""Response message for BatchGetAccessBindings RPC. + + Attributes: + access_bindings (MutableSequence[google.analytics.admin_v1alpha.types.AccessBinding]): + The requested access bindings. + """ + + access_bindings: MutableSequence[resources.AccessBinding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.AccessBinding, + ) + + +class ListAccessBindingsRequest(proto.Message): + r"""Request message for ListAccessBindings RPC. + + Attributes: + parent (str): + Required. Formats: + + - accounts/{account} + - properties/{property} + page_size (int): + The maximum number of access bindings to + return. The service may return fewer than this + value. If unspecified, at most 200 access + bindings will be returned. The maximum value is + 500; values above 500 will be coerced to 500. + page_token (str): + A page token, received from a previous + ``ListAccessBindings`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListAccessBindings`` must match the call that + provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAccessBindingsResponse(proto.Message): + r"""Response message for ListAccessBindings RPC. + + Attributes: + access_bindings (MutableSequence[google.analytics.admin_v1alpha.types.AccessBinding]): + List of AccessBindings. These will be ordered + stably, but in an arbitrary order. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + access_bindings: MutableSequence[resources.AccessBinding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.AccessBinding, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateAccessBindingRequest(proto.Message): + r"""Request message for CreateAccessBinding RPC. + + Attributes: + parent (str): + Required. Formats: + + - accounts/{account} + - properties/{property} + access_binding (google.analytics.admin_v1alpha.types.AccessBinding): + Required. The access binding to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + access_binding: resources.AccessBinding = proto.Field( + proto.MESSAGE, + number=2, + message=resources.AccessBinding, + ) + + +class BatchCreateAccessBindingsRequest(proto.Message): + r"""Request message for BatchCreateAccessBindings RPC. + + Attributes: + parent (str): + Required. The account or property that owns + the access bindings. The parent field in the + CreateAccessBindingRequest messages must either + be empty or match this field. Formats: + + - accounts/{account} + - properties/{property} + requests (MutableSequence[google.analytics.admin_v1alpha.types.CreateAccessBindingRequest]): + Required. The requests specifying the access + bindings to create. A maximum of 1000 access + bindings can be created in a batch. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['CreateAccessBindingRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='CreateAccessBindingRequest', + ) + + +class BatchCreateAccessBindingsResponse(proto.Message): + r"""Response message for BatchCreateAccessBindings RPC. + + Attributes: + access_bindings (MutableSequence[google.analytics.admin_v1alpha.types.AccessBinding]): + The access bindings created. + """ + + access_bindings: MutableSequence[resources.AccessBinding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.AccessBinding, + ) + + +class UpdateAccessBindingRequest(proto.Message): + r"""Request message for UpdateAccessBinding RPC. + + Attributes: + access_binding (google.analytics.admin_v1alpha.types.AccessBinding): + Required. The access binding to update. + """ + + access_binding: resources.AccessBinding = proto.Field( + proto.MESSAGE, + number=1, + message=resources.AccessBinding, + ) + + +class BatchUpdateAccessBindingsRequest(proto.Message): + r"""Request message for BatchUpdateAccessBindings RPC. + + Attributes: + parent (str): + Required. The account or property that owns + the access bindings. The parent of all provided + AccessBinding in UpdateAccessBindingRequest + messages must match this field. + Formats: + + - accounts/{account} + - properties/{property} + requests (MutableSequence[google.analytics.admin_v1alpha.types.UpdateAccessBindingRequest]): + Required. The requests specifying the access + bindings to update. A maximum of 1000 access + bindings can be updated in a batch. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['UpdateAccessBindingRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='UpdateAccessBindingRequest', + ) + + +class BatchUpdateAccessBindingsResponse(proto.Message): + r"""Response message for BatchUpdateAccessBindings RPC. + + Attributes: + access_bindings (MutableSequence[google.analytics.admin_v1alpha.types.AccessBinding]): + The access bindings updated. + """ + + access_bindings: MutableSequence[resources.AccessBinding] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.AccessBinding, + ) + + +class DeleteAccessBindingRequest(proto.Message): + r"""Request message for DeleteAccessBinding RPC. + + Attributes: + name (str): + Required. Formats: + + - + accounts/{account}/accessBindings/{accessBinding} + - + properties/{property}/accessBindings/{accessBinding} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BatchDeleteAccessBindingsRequest(proto.Message): + r"""Request message for BatchDeleteAccessBindings RPC. + + Attributes: + parent (str): + Required. The account or property that owns + the access bindings. The parent of all provided + values for the 'names' field in + DeleteAccessBindingRequest messages must match + this field. Formats: + + - accounts/{account} + - properties/{property} + requests (MutableSequence[google.analytics.admin_v1alpha.types.DeleteAccessBindingRequest]): + Required. The requests specifying the access + bindings to delete. A maximum of 1000 access + bindings can be deleted in a batch. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence['DeleteAccessBindingRequest'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='DeleteAccessBindingRequest', + ) + + +class CreateExpandedDataSetRequest(proto.Message): + r"""Request message for CreateExpandedDataSet RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + expanded_data_set (google.analytics.admin_v1alpha.types.ExpandedDataSet): + Required. The ExpandedDataSet to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + expanded_data_set: gaa_expanded_data_set.ExpandedDataSet = proto.Field( + proto.MESSAGE, + number=2, + message=gaa_expanded_data_set.ExpandedDataSet, + ) + + +class UpdateExpandedDataSetRequest(proto.Message): + r"""Request message for UpdateExpandedDataSet RPC. + + Attributes: + expanded_data_set (google.analytics.admin_v1alpha.types.ExpandedDataSet): + Required. The ExpandedDataSet to update. The resource's + ``name`` field is used to identify the ExpandedDataSet to be + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + expanded_data_set: gaa_expanded_data_set.ExpandedDataSet = proto.Field( + proto.MESSAGE, + number=1, + message=gaa_expanded_data_set.ExpandedDataSet, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteExpandedDataSetRequest(proto.Message): + r"""Request message for DeleteExpandedDataSet RPC. + + Attributes: + name (str): + Required. Example format: + properties/1234/expandedDataSets/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetExpandedDataSetRequest(proto.Message): + r"""Request message for GetExpandedDataSet RPC. + + Attributes: + name (str): + Required. The name of the ExpandedDataSet to + get. Example format: + properties/1234/expandedDataSets/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListExpandedDataSetsRequest(proto.Message): + r"""Request message for ListExpandedDataSets RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous + ``ListExpandedDataSets`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListExpandedDataSet`` must match the call that provided + the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListExpandedDataSetsResponse(proto.Message): + r"""Response message for ListExpandedDataSets RPC. + + Attributes: + expanded_data_sets (MutableSequence[google.analytics.admin_v1alpha.types.ExpandedDataSet]): + List of ExpandedDataSet. These will be + ordered stably, but in an arbitrary order. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + expanded_data_sets: MutableSequence[gaa_expanded_data_set.ExpandedDataSet] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gaa_expanded_data_set.ExpandedDataSet, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateChannelGroupRequest(proto.Message): + r"""Request message for CreateChannelGroup RPC. + + Attributes: + parent (str): + Required. The property for which to create a + ChannelGroup. Example format: properties/1234 + channel_group (google.analytics.admin_v1alpha.types.ChannelGroup): + Required. The ChannelGroup to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + channel_group: gaa_channel_group.ChannelGroup = proto.Field( + proto.MESSAGE, + number=2, + message=gaa_channel_group.ChannelGroup, + ) + + +class UpdateChannelGroupRequest(proto.Message): + r"""Request message for UpdateChannelGroup RPC. + + Attributes: + channel_group (google.analytics.admin_v1alpha.types.ChannelGroup): + Required. The ChannelGroup to update. The resource's + ``name`` field is used to identify the ChannelGroup to be + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + channel_group: gaa_channel_group.ChannelGroup = proto.Field( + proto.MESSAGE, + number=1, + message=gaa_channel_group.ChannelGroup, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteChannelGroupRequest(proto.Message): + r"""Request message for DeleteChannelGroup RPC. + + Attributes: + name (str): + Required. The ChannelGroup to delete. + Example format: + properties/1234/channelGroups/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetChannelGroupRequest(proto.Message): + r"""Request message for GetChannelGroup RPC. + + Attributes: + name (str): + Required. The ChannelGroup to get. + Example format: + properties/1234/channelGroups/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListChannelGroupsRequest(proto.Message): + r"""Request message for ListChannelGroups RPC. + + Attributes: + parent (str): + Required. The property for which to list + ChannelGroups. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous ``ListChannelGroups`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListChannelGroups`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListChannelGroupsResponse(proto.Message): + r"""Response message for ListChannelGroups RPC. + + Attributes: + channel_groups (MutableSequence[google.analytics.admin_v1alpha.types.ChannelGroup]): + List of ChannelGroup. These will be ordered + stably, but in an arbitrary order. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + channel_groups: MutableSequence[gaa_channel_group.ChannelGroup] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gaa_channel_group.ChannelGroup, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SetAutomatedGa4ConfigurationOptOutRequest(proto.Message): + r"""Request for setting the opt out status for the automated GA4 + setup process. + + Attributes: + property (str): + Required. The UA property to set the opt out + status. Note this request uses the internal + property ID, not the tracking ID of the form + UA-XXXXXX-YY. Format: + properties/{internalWebPropertyId} + Example: properties/1234 + opt_out (bool): + The status to set. + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + opt_out: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class SetAutomatedGa4ConfigurationOptOutResponse(proto.Message): + r"""Response message for setting the opt out status for the + automated GA4 setup process. + + """ + + +class FetchAutomatedGa4ConfigurationOptOutRequest(proto.Message): + r"""Request for fetching the opt out status for the automated GA4 + setup process. + + Attributes: + property (str): + Required. The UA property to get the opt out + status. Note this request uses the internal + property ID, not the tracking ID of the form + UA-XXXXXX-YY. Format: + properties/{internalWebPropertyId} + Example: properties/1234 + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchAutomatedGa4ConfigurationOptOutResponse(proto.Message): + r"""Response message for fetching the opt out status for the + automated GA4 setup process. + + Attributes: + opt_out (bool): + The opt out status for the UA property. + """ + + opt_out: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class CreateBigQueryLinkRequest(proto.Message): + r"""Request message for CreateBigQueryLink RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + bigquery_link (google.analytics.admin_v1alpha.types.BigQueryLink): + Required. The BigQueryLink to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + bigquery_link: resources.BigQueryLink = proto.Field( + proto.MESSAGE, + number=2, + message=resources.BigQueryLink, + ) + + +class GetBigQueryLinkRequest(proto.Message): + r"""Request message for GetBigQueryLink RPC. + + Attributes: + name (str): + Required. The name of the BigQuery link to lookup. Format: + properties/{property_id}/bigQueryLinks/{bigquery_link_id} + Example: properties/123/bigQueryLinks/456 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListBigQueryLinksRequest(proto.Message): + r"""Request message for ListBigQueryLinks RPC. + + Attributes: + parent (str): + Required. The name of the property to list BigQuery links + under. Format: properties/{property_id} Example: + properties/1234 + page_size (int): + The maximum number of resources to return. + The service may return fewer than this value, + even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListBigQueryLinks`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListBigQueryLinks`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListBigQueryLinksResponse(proto.Message): + r"""Response message for ListBigQueryLinks RPC + + Attributes: + bigquery_links (MutableSequence[google.analytics.admin_v1alpha.types.BigQueryLink]): + List of BigQueryLinks. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + bigquery_links: MutableSequence[resources.BigQueryLink] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.BigQueryLink, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateBigQueryLinkRequest(proto.Message): + r"""Request message for UpdateBigQueryLink RPC. + + Attributes: + bigquery_link (google.analytics.admin_v1alpha.types.BigQueryLink): + Required. The settings to update. The ``name`` field is used + to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + bigquery_link: resources.BigQueryLink = proto.Field( + proto.MESSAGE, + number=1, + message=resources.BigQueryLink, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteBigQueryLinkRequest(proto.Message): + r"""Request message for DeleteBigQueryLink RPC. + + Attributes: + name (str): + Required. The BigQueryLink to delete. + Example format: + properties/1234/bigQueryLinks/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEnhancedMeasurementSettingsRequest(proto.Message): + r"""Request message for GetEnhancedMeasurementSettings RPC. + + Attributes: + name (str): + Required. The name of the settings to lookup. Format: + properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings + Example: + "properties/1000/dataStreams/2000/enhancedMeasurementSettings". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateEnhancedMeasurementSettingsRequest(proto.Message): + r"""Request message for UpdateEnhancedMeasurementSettings RPC. + + Attributes: + enhanced_measurement_settings (google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings): + Required. The settings to update. The ``name`` field is used + to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + enhanced_measurement_settings: resources.EnhancedMeasurementSettings = proto.Field( + proto.MESSAGE, + number=1, + message=resources.EnhancedMeasurementSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetDataRedactionSettingsRequest(proto.Message): + r"""Request message for GetDataRedactionSettings RPC. + + Attributes: + name (str): + Required. The name of the settings to lookup. Format: + properties/{property}/dataStreams/{data_stream}/dataRedactionSettings + Example: + "properties/1000/dataStreams/2000/dataRedactionSettings". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDataRedactionSettingsRequest(proto.Message): + r"""Request message for UpdateDataRedactionSettings RPC. + + Attributes: + data_redaction_settings (google.analytics.admin_v1alpha.types.DataRedactionSettings): + Required. The settings to update. The ``name`` field is used + to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + data_redaction_settings: resources.DataRedactionSettings = proto.Field( + proto.MESSAGE, + number=1, + message=resources.DataRedactionSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CreateConnectedSiteTagRequest(proto.Message): + r"""Request message for CreateConnectedSiteTag RPC. + + Attributes: + property (str): + The Universal Analytics property to create + connected site tags for. This API does not + support GA4 properties. Format: + properties/{universalAnalyticsPropertyId} + Example: properties/1234 + connected_site_tag (google.analytics.admin_v1alpha.types.ConnectedSiteTag): + Required. The tag to add to the Universal + Analytics property + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + connected_site_tag: resources.ConnectedSiteTag = proto.Field( + proto.MESSAGE, + number=2, + message=resources.ConnectedSiteTag, + ) + + +class CreateConnectedSiteTagResponse(proto.Message): + r"""Response message for CreateConnectedSiteTag RPC. + """ + + +class DeleteConnectedSiteTagRequest(proto.Message): + r"""Request message for DeleteConnectedSiteTag RPC. + + Attributes: + property (str): + The Universal Analytics property to delete + connected site tags for. This API does not + support GA4 properties. Format: + properties/{universalAnalyticsPropertyId} + Example: properties/1234 + tag_id (str): + Tag ID to forward events to. Also known as + the Measurement ID, or the "G-ID" (For example: + G-12345). + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + tag_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListConnectedSiteTagsRequest(proto.Message): + r"""Request message for ListConnectedSiteTags RPC. + + Attributes: + property (str): + The Universal Analytics property to fetch connected site + tags for. This does not work on GA4 properties. A maximum of + 20 connected site tags will be returned. Example Format: + ``properties/1234`` + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListConnectedSiteTagsResponse(proto.Message): + r"""Response message for ListConnectedSiteTags RPC. + + Attributes: + connected_site_tags (MutableSequence[google.analytics.admin_v1alpha.types.ConnectedSiteTag]): + The site tags for the Universal Analytics + property. A maximum of 20 connected site tags + will be returned. + """ + + connected_site_tags: MutableSequence[resources.ConnectedSiteTag] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.ConnectedSiteTag, + ) + + +class CreateAdSenseLinkRequest(proto.Message): + r"""Request message to be passed to CreateAdSenseLink method. + + Attributes: + parent (str): + Required. The property for which to create an + AdSense Link. Format: properties/{propertyId} + Example: properties/1234 + adsense_link (google.analytics.admin_v1alpha.types.AdSenseLink): + Required. The AdSense Link to create + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + adsense_link: resources.AdSenseLink = proto.Field( + proto.MESSAGE, + number=2, + message=resources.AdSenseLink, + ) + + +class GetAdSenseLinkRequest(proto.Message): + r"""Request message to be passed to GetAdSenseLink method. + + Attributes: + name (str): + Required. Unique identifier for the AdSense + Link requested. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: properties/1234/adSenseLinks/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteAdSenseLinkRequest(proto.Message): + r"""Request message to be passed to DeleteAdSenseLink method. + + Attributes: + name (str): + Required. Unique identifier for the AdSense + Link to be deleted. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: properties/1234/adSenseLinks/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAdSenseLinksRequest(proto.Message): + r"""Request message to be passed to ListAdSenseLinks method. + + Attributes: + parent (str): + Required. Resource name of the parent + property. Format: properties/{propertyId} + Example: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token received from a previous ``ListAdSenseLinks`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListAdSenseLinks`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAdSenseLinksResponse(proto.Message): + r"""Response message for ListAdSenseLinks method. + + Attributes: + adsense_links (MutableSequence[google.analytics.admin_v1alpha.types.AdSenseLink]): + List of AdSenseLinks. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + adsense_links: MutableSequence[resources.AdSenseLink] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.AdSenseLink, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class FetchConnectedGa4PropertyRequest(proto.Message): + r"""Request for looking up GA4 property connected to a UA + property. + + Attributes: + property (str): + Required. The UA property for which to look up the connected + GA4 property. Note this request uses the internal property + ID, not the tracking ID of the form UA-XXXXXX-YY. Format: + properties/{internal_web_property_id} Example: + properties/1234 + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FetchConnectedGa4PropertyResponse(proto.Message): + r"""Response for looking up GA4 property connected to a UA + property. + + Attributes: + property (str): + The GA4 property connected to the UA property. An empty + string is returned when there is no connected GA4 property. + Format: properties/{property_id} Example: properties/1234 + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEventCreateRuleRequest(proto.Message): + r"""Request message for CreateEventCreateRule RPC. + + Attributes: + parent (str): + Required. Example format: + properties/123/dataStreams/456 + event_create_rule (google.analytics.admin_v1alpha.types.EventCreateRule): + Required. The EventCreateRule to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + event_create_rule: event_create_and_edit.EventCreateRule = proto.Field( + proto.MESSAGE, + number=2, + message=event_create_and_edit.EventCreateRule, + ) + + +class UpdateEventCreateRuleRequest(proto.Message): + r"""Request message for UpdateEventCreateRule RPC. + + Attributes: + event_create_rule (google.analytics.admin_v1alpha.types.EventCreateRule): + Required. The EventCreateRule to update. The resource's + ``name`` field is used to identify the EventCreateRule to be + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + event_create_rule: event_create_and_edit.EventCreateRule = proto.Field( + proto.MESSAGE, + number=1, + message=event_create_and_edit.EventCreateRule, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEventCreateRuleRequest(proto.Message): + r"""Request message for DeleteEventCreateRule RPC. + + Attributes: + name (str): + Required. Example format: + + properties/123/dataStreams/456/eventCreateRules/789 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEventCreateRuleRequest(proto.Message): + r"""Request message for GetEventCreateRule RPC. + + Attributes: + name (str): + Required. The name of the EventCreateRule to + get. Example format: + properties/123/dataStreams/456/eventCreateRules/789 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEventCreateRulesRequest(proto.Message): + r"""Request message for ListEventCreateRules RPC. + + Attributes: + parent (str): + Required. Example format: + properties/123/dataStreams/456 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous + ``ListEventCreateRules`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListEventCreateRules`` must match the call that provided + the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEventCreateRulesResponse(proto.Message): + r"""Response message for ListEventCreateRules RPC. + + Attributes: + event_create_rules (MutableSequence[google.analytics.admin_v1alpha.types.EventCreateRule]): + List of EventCreateRules. These will be + ordered stably, but in an arbitrary order. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + event_create_rules: MutableSequence[event_create_and_edit.EventCreateRule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=event_create_and_edit.EventCreateRule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateEventEditRuleRequest(proto.Message): + r"""Request message for CreateEventEditRule RPC. + + Attributes: + parent (str): + Required. Example format: + properties/123/dataStreams/456 + event_edit_rule (google.analytics.admin_v1alpha.types.EventEditRule): + Required. The EventEditRule to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + event_edit_rule: event_create_and_edit.EventEditRule = proto.Field( + proto.MESSAGE, + number=2, + message=event_create_and_edit.EventEditRule, + ) + + +class UpdateEventEditRuleRequest(proto.Message): + r"""Request message for UpdateEventEditRule RPC. + + Attributes: + event_edit_rule (google.analytics.admin_v1alpha.types.EventEditRule): + Required. The EventEditRule to update. The resource's + ``name`` field is used to identify the EventEditRule to be + updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + event_edit_rule: event_create_and_edit.EventEditRule = proto.Field( + proto.MESSAGE, + number=1, + message=event_create_and_edit.EventEditRule, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEventEditRuleRequest(proto.Message): + r"""Request message for DeleteEventEditRule RPC. + + Attributes: + name (str): + Required. Example format: + properties/123/dataStreams/456/eventEditRules/789 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEventEditRuleRequest(proto.Message): + r"""Request message for GetEventEditRule RPC. + + Attributes: + name (str): + Required. The name of the EventEditRule to + get. Example format: + properties/123/dataStreams/456/eventEditRules/789 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEventEditRulesRequest(proto.Message): + r"""Request message for ListEventEditRules RPC. + + Attributes: + parent (str): + Required. Example format: + properties/123/dataStreams/456 + page_size (int): + Optional. The maximum number of resources to + return. If unspecified, at most 50 resources + will be returned. The maximum value is 200 + (higher values will be coerced to the maximum). + page_token (str): + Optional. A page token, received from a previous + ``ListEventEditRules`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListEventEditRules`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEventEditRulesResponse(proto.Message): + r"""Response message for ListEventEditRules RPC. + + Attributes: + event_edit_rules (MutableSequence[google.analytics.admin_v1alpha.types.EventEditRule]): + List of EventEditRules. These will be ordered + stably, but in an arbitrary order. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + event_edit_rules: MutableSequence[event_create_and_edit.EventEditRule] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=event_create_and_edit.EventEditRule, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ReorderEventEditRulesRequest(proto.Message): + r"""Request message for ReorderEventEditRules RPC. + + Attributes: + parent (str): + Required. Example format: + properties/123/dataStreams/456 + event_edit_rules (MutableSequence[str]): + Required. EventEditRule resource names for + the specified data stream, in the needed + processing order. All EventEditRules for the + stream must be present in the list. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + event_edit_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CreateRollupPropertyRequest(proto.Message): + r"""Request message for CreateRollupProperty RPC. + + Attributes: + rollup_property (google.analytics.admin_v1alpha.types.Property): + Required. The roll-up property to create. + source_properties (MutableSequence[str]): + Optional. The resource names of properties + that will be sources to the created roll-up + property. + """ + + rollup_property: resources.Property = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Property, + ) + source_properties: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CreateRollupPropertyResponse(proto.Message): + r"""Response message for CreateRollupProperty RPC. + + Attributes: + rollup_property (google.analytics.admin_v1alpha.types.Property): + The created roll-up property. + rollup_property_source_links (MutableSequence[google.analytics.admin_v1alpha.types.RollupPropertySourceLink]): + The created roll-up property source links. + """ + + rollup_property: resources.Property = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Property, + ) + rollup_property_source_links: MutableSequence[resources.RollupPropertySourceLink] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=resources.RollupPropertySourceLink, + ) + + +class GetRollupPropertySourceLinkRequest(proto.Message): + r"""Request message for GetRollupPropertySourceLink RPC. + + Attributes: + name (str): + Required. The name of the roll-up property source link to + lookup. Format: + properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} + Example: properties/123/rollupPropertySourceLinks/456 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRollupPropertySourceLinksRequest(proto.Message): + r"""Request message for ListRollupPropertySourceLinks RPC. + + Attributes: + parent (str): + Required. The name of the roll-up property to list roll-up + property source links under. Format: + properties/{property_id} Example: properties/1234 + page_size (int): + Optional. The maximum number of resources to + return. The service may return fewer than this + value, even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + Optional. A page token, received from a previous + ``ListRollupPropertySourceLinks`` call. Provide this to + retrieve the subsequent page. When paginating, all other + parameters provided to ``ListRollupPropertySourceLinks`` + must match the call that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListRollupPropertySourceLinksResponse(proto.Message): + r"""Response message for ListRollupPropertySourceLinks RPC. + + Attributes: + rollup_property_source_links (MutableSequence[google.analytics.admin_v1alpha.types.RollupPropertySourceLink]): + List of RollupPropertySourceLinks. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + rollup_property_source_links: MutableSequence[resources.RollupPropertySourceLink] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.RollupPropertySourceLink, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateRollupPropertySourceLinkRequest(proto.Message): + r"""Request message for CreateRollupPropertySourceLink RPC. + + Attributes: + parent (str): + Required. Format: properties/{property_id} Example: + properties/1234 + rollup_property_source_link (google.analytics.admin_v1alpha.types.RollupPropertySourceLink): + Required. The roll-up property source link to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + rollup_property_source_link: resources.RollupPropertySourceLink = proto.Field( + proto.MESSAGE, + number=2, + message=resources.RollupPropertySourceLink, + ) + + +class DeleteRollupPropertySourceLinkRequest(proto.Message): + r"""Request message for DeleteRollupPropertySourceLink RPC. + + Attributes: + name (str): + Required. Format: + properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link_id} + Example: properties/1234/rollupPropertySourceLinks/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ProvisionSubpropertyRequest(proto.Message): + r"""Request message for CreateSubproperty RPC. + + Attributes: + subproperty (google.analytics.admin_v1alpha.types.Property): + Required. The subproperty to create. + subproperty_event_filter (google.analytics.admin_v1alpha.types.SubpropertyEventFilter): + Optional. The subproperty event filter to + create on an ordinary property. + """ + + subproperty: resources.Property = proto.Field( + proto.MESSAGE, + number=2, + message=resources.Property, + ) + subproperty_event_filter: gaa_subproperty_event_filter.SubpropertyEventFilter = proto.Field( + proto.MESSAGE, + number=3, + message=gaa_subproperty_event_filter.SubpropertyEventFilter, + ) + + +class ProvisionSubpropertyResponse(proto.Message): + r"""Response message for ProvisionSubproperty RPC. + + Attributes: + subproperty (google.analytics.admin_v1alpha.types.Property): + The created subproperty. + subproperty_event_filter (google.analytics.admin_v1alpha.types.SubpropertyEventFilter): + The created subproperty event filter. + """ + + subproperty: resources.Property = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Property, + ) + subproperty_event_filter: gaa_subproperty_event_filter.SubpropertyEventFilter = proto.Field( + proto.MESSAGE, + number=2, + message=gaa_subproperty_event_filter.SubpropertyEventFilter, + ) + + +class CreateSubpropertyEventFilterRequest(proto.Message): + r"""Request message for CreateSubpropertyEventFilter RPC. + + Attributes: + parent (str): + Required. The ordinary property for which to create a + subproperty event filter. Format: properties/property_id + Example: properties/123 + subproperty_event_filter (google.analytics.admin_v1alpha.types.SubpropertyEventFilter): + Required. The subproperty event filter to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + subproperty_event_filter: gaa_subproperty_event_filter.SubpropertyEventFilter = proto.Field( + proto.MESSAGE, + number=2, + message=gaa_subproperty_event_filter.SubpropertyEventFilter, + ) + + +class GetSubpropertyEventFilterRequest(proto.Message): + r"""Request message for GetSubpropertyEventFilter RPC. + + Attributes: + name (str): + Required. Resource name of the subproperty event filter to + lookup. Format: + properties/property_id/subpropertyEventFilters/subproperty_event_filter + Example: properties/123/subpropertyEventFilters/456 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSubpropertyEventFiltersRequest(proto.Message): + r"""Request message for ListSubpropertyEventFilters RPC. + + Attributes: + parent (str): + Required. Resource name of the ordinary property. Format: + properties/property_id Example: properties/123 + page_size (int): + Optional. The maximum number of resources to + return. The service may return fewer than this + value, even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + Optional. A page token, received from a previous + ``ListSubpropertyEventFilters`` call. Provide this to + retrieve the subsequent page. When paginating, all other + parameters provided to ``ListSubpropertyEventFilters`` must + match the call that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSubpropertyEventFiltersResponse(proto.Message): + r"""Response message for ListSubpropertyEventFilter RPC. + + Attributes: + subproperty_event_filters (MutableSequence[google.analytics.admin_v1alpha.types.SubpropertyEventFilter]): + List of subproperty event filters. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + subproperty_event_filters: MutableSequence[gaa_subproperty_event_filter.SubpropertyEventFilter] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gaa_subproperty_event_filter.SubpropertyEventFilter, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateSubpropertyEventFilterRequest(proto.Message): + r"""Request message for UpdateSubpropertyEventFilter RPC. + + Attributes: + subproperty_event_filter (google.analytics.admin_v1alpha.types.SubpropertyEventFilter): + Required. The subproperty event filter to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. Field names must be + in snake case (for example, "field_to_update"). Omitted + fields will not be updated. To replace the entire entity, + use one path with the string "*" to match all fields. + """ + + subproperty_event_filter: gaa_subproperty_event_filter.SubpropertyEventFilter = proto.Field( + proto.MESSAGE, + number=1, + message=gaa_subproperty_event_filter.SubpropertyEventFilter, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSubpropertyEventFilterRequest(proto.Message): + r"""Request message for DeleteSubpropertyEventFilter RPC. + + Attributes: + name (str): + Required. Resource name of the subproperty event filter to + delete. Format: + properties/property_id/subpropertyEventFilters/subproperty_event_filter + Example: properties/123/subpropertyEventFilters/456 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/audience.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/audience.py new file mode 100644 index 000000000000..d03daa06b0df --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/audience.py @@ -0,0 +1,772 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.analytics.admin.v1alpha', + manifest={ + 'AudienceFilterScope', + 'AudienceDimensionOrMetricFilter', + 'AudienceEventFilter', + 'AudienceFilterExpression', + 'AudienceFilterExpressionList', + 'AudienceSimpleFilter', + 'AudienceSequenceFilter', + 'AudienceFilterClause', + 'AudienceEventTrigger', + 'Audience', + }, +) + + +class AudienceFilterScope(proto.Enum): + r"""Specifies how to evaluate users for joining an Audience. + + Values: + AUDIENCE_FILTER_SCOPE_UNSPECIFIED (0): + Scope is not specified. + AUDIENCE_FILTER_SCOPE_WITHIN_SAME_EVENT (1): + User joins the Audience if the filter + condition is met within one event. + AUDIENCE_FILTER_SCOPE_WITHIN_SAME_SESSION (2): + User joins the Audience if the filter + condition is met within one session. + AUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS (3): + User joins the Audience if the filter + condition is met by any event across any + session. + """ + AUDIENCE_FILTER_SCOPE_UNSPECIFIED = 0 + AUDIENCE_FILTER_SCOPE_WITHIN_SAME_EVENT = 1 + AUDIENCE_FILTER_SCOPE_WITHIN_SAME_SESSION = 2 + AUDIENCE_FILTER_SCOPE_ACROSS_ALL_SESSIONS = 3 + + +class AudienceDimensionOrMetricFilter(proto.Message): + r"""A specific filter for a single dimension or metric. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_filter (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter.StringFilter): + A filter for a string-type dimension that + matches a particular pattern. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter.InListFilter): + A filter for a string dimension that matches + a particular list of options. + + This field is a member of `oneof`_ ``one_filter``. + numeric_filter (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter.NumericFilter): + A filter for numeric or date values on a + dimension or metric. + + This field is a member of `oneof`_ ``one_filter``. + between_filter (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter.BetweenFilter): + A filter for numeric or date values between + certain values on a dimension or metric. + + This field is a member of `oneof`_ ``one_filter``. + field_name (str): + Required. Immutable. The dimension name or metric name to + filter. If the field name refers to a custom dimension or + metric, a scope prefix will be added to the front of the + custom dimensions or metric name. For more on scope prefixes + or custom dimensions/metrics, reference the [Google + Analytics Data API documentation] + (https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#custom_dimensions). + at_any_point_in_time (bool): + Optional. Indicates whether this filter needs dynamic + evaluation or not. If set to true, users join the Audience + if they ever met the condition (static evaluation). If unset + or set to false, user evaluation for an Audience is dynamic; + users are added to an Audience when they meet the conditions + and then removed when they no longer meet them. + + This can only be set when Audience scope is + ACROSS_ALL_SESSIONS. + in_any_n_day_period (int): + Optional. If set, specifies the time window for which to + evaluate data in number of days. If not set, then audience + data is evaluated against lifetime data (For example, + infinite time window). + + For example, if set to 1 day, only the current day's data is + evaluated. The reference point is the current day when + at_any_point_in_time is unset or false. + + It can only be set when Audience scope is + ACROSS_ALL_SESSIONS and cannot be greater than 60 days. + """ + + class StringFilter(proto.Message): + r"""A filter for a string-type dimension that matches a + particular pattern. + + Attributes: + match_type (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter.StringFilter.MatchType): + Required. The match type for the string + filter. + value (str): + Required. The string value to be matched + against. + case_sensitive (bool): + Optional. If true, the match is + case-sensitive. If false, the match is + case-insensitive. + """ + class MatchType(proto.Enum): + r"""The match type for the string filter. + + Values: + MATCH_TYPE_UNSPECIFIED (0): + Unspecified + EXACT (1): + Exact match of the string value. + BEGINS_WITH (2): + Begins with the string value. + ENDS_WITH (3): + Ends with the string value. + CONTAINS (4): + Contains the string value. + FULL_REGEXP (5): + Full regular expression matches with the + string value. + """ + MATCH_TYPE_UNSPECIFIED = 0 + EXACT = 1 + BEGINS_WITH = 2 + ENDS_WITH = 3 + CONTAINS = 4 + FULL_REGEXP = 5 + + match_type: 'AudienceDimensionOrMetricFilter.StringFilter.MatchType' = proto.Field( + proto.ENUM, + number=1, + enum='AudienceDimensionOrMetricFilter.StringFilter.MatchType', + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class InListFilter(proto.Message): + r"""A filter for a string dimension that matches a particular + list of options. + + Attributes: + values (MutableSequence[str]): + Required. The list of possible string values + to match against. Must be non-empty. + case_sensitive (bool): + Optional. If true, the match is + case-sensitive. If false, the match is + case-insensitive. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class NumericValue(proto.Message): + r"""To represent a number. + + 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: + int64_value (int): + Integer value. + + This field is a member of `oneof`_ ``one_value``. + double_value (float): + Double value. + + This field is a member of `oneof`_ ``one_value``. + """ + + int64_value: int = proto.Field( + proto.INT64, + number=1, + oneof='one_value', + ) + double_value: float = proto.Field( + proto.DOUBLE, + number=2, + oneof='one_value', + ) + + class NumericFilter(proto.Message): + r"""A filter for numeric or date values on a dimension or metric. + + Attributes: + operation (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter.NumericFilter.Operation): + Required. The operation applied to a numeric + filter. + value (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter.NumericValue): + Required. The numeric or date value to match + against. + """ + class Operation(proto.Enum): + r"""The operation applied to a numeric filter. + + Values: + OPERATION_UNSPECIFIED (0): + Unspecified. + EQUAL (1): + Equal. + LESS_THAN (2): + Less than. + GREATER_THAN (4): + Greater than. + """ + OPERATION_UNSPECIFIED = 0 + EQUAL = 1 + LESS_THAN = 2 + GREATER_THAN = 4 + + operation: 'AudienceDimensionOrMetricFilter.NumericFilter.Operation' = proto.Field( + proto.ENUM, + number=1, + enum='AudienceDimensionOrMetricFilter.NumericFilter.Operation', + ) + value: 'AudienceDimensionOrMetricFilter.NumericValue' = proto.Field( + proto.MESSAGE, + number=2, + message='AudienceDimensionOrMetricFilter.NumericValue', + ) + + class BetweenFilter(proto.Message): + r"""A filter for numeric or date values between certain values on + a dimension or metric. + + Attributes: + from_value (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter.NumericValue): + Required. Begins with this number, inclusive. + to_value (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter.NumericValue): + Required. Ends with this number, inclusive. + """ + + from_value: 'AudienceDimensionOrMetricFilter.NumericValue' = proto.Field( + proto.MESSAGE, + number=1, + message='AudienceDimensionOrMetricFilter.NumericValue', + ) + to_value: 'AudienceDimensionOrMetricFilter.NumericValue' = proto.Field( + proto.MESSAGE, + number=2, + message='AudienceDimensionOrMetricFilter.NumericValue', + ) + + string_filter: StringFilter = proto.Field( + proto.MESSAGE, + number=2, + oneof='one_filter', + message=StringFilter, + ) + in_list_filter: InListFilter = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_filter', + message=InListFilter, + ) + numeric_filter: NumericFilter = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_filter', + message=NumericFilter, + ) + between_filter: BetweenFilter = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_filter', + message=BetweenFilter, + ) + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + at_any_point_in_time: bool = proto.Field( + proto.BOOL, + number=6, + ) + in_any_n_day_period: int = proto.Field( + proto.INT32, + number=7, + ) + + +class AudienceEventFilter(proto.Message): + r"""A filter that matches events of a single event name. If an + event parameter is specified, only the subset of events that + match both the single event name and the parameter filter + expressions match this event filter. + + Attributes: + event_name (str): + Required. Immutable. The name of the event to + match against. + event_parameter_filter_expression (google.analytics.admin_v1alpha.types.AudienceFilterExpression): + Optional. If specified, this filter matches events that + match both the single event name and the parameter filter + expressions. AudienceEventFilter inside the parameter filter + expression cannot be set (For example, nested event filters + are not supported). This should be a single and_group of + dimension_or_metric_filter or not_expression; ANDs of ORs + are not supported. Also, if it includes a filter for + "eventCount", only that one will be considered; all the + other filters will be ignored. + """ + + event_name: str = proto.Field( + proto.STRING, + number=1, + ) + event_parameter_filter_expression: 'AudienceFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + message='AudienceFilterExpression', + ) + + +class AudienceFilterExpression(proto.Message): + r"""A logical expression of Audience dimension, metric, or event + filters. + + 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: + and_group (google.analytics.admin_v1alpha.types.AudienceFilterExpressionList): + A list of expressions to be AND’ed together. It can only + contain AudienceFilterExpressions with or_group. This must + be set for the top level AudienceFilterExpression. + + This field is a member of `oneof`_ ``expr``. + or_group (google.analytics.admin_v1alpha.types.AudienceFilterExpressionList): + A list of expressions to OR’ed together. It cannot contain + AudienceFilterExpressions with and_group or or_group. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.admin_v1alpha.types.AudienceFilterExpression): + A filter expression to be NOT'ed (For example, inverted, + complemented). It can only include a + dimension_or_metric_filter. This cannot be set on the top + level AudienceFilterExpression. + + This field is a member of `oneof`_ ``expr``. + dimension_or_metric_filter (google.analytics.admin_v1alpha.types.AudienceDimensionOrMetricFilter): + A filter on a single dimension or metric. + This cannot be set on the top level + AudienceFilterExpression. + + This field is a member of `oneof`_ ``expr``. + event_filter (google.analytics.admin_v1alpha.types.AudienceEventFilter): + Creates a filter that matches a specific + event. This cannot be set on the top level + AudienceFilterExpression. + + This field is a member of `oneof`_ ``expr``. + """ + + and_group: 'AudienceFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='AudienceFilterExpressionList', + ) + or_group: 'AudienceFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='AudienceFilterExpressionList', + ) + not_expression: 'AudienceFilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='AudienceFilterExpression', + ) + dimension_or_metric_filter: 'AudienceDimensionOrMetricFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='expr', + message='AudienceDimensionOrMetricFilter', + ) + event_filter: 'AudienceEventFilter' = proto.Field( + proto.MESSAGE, + number=5, + oneof='expr', + message='AudienceEventFilter', + ) + + +class AudienceFilterExpressionList(proto.Message): + r"""A list of Audience filter expressions. + + Attributes: + filter_expressions (MutableSequence[google.analytics.admin_v1alpha.types.AudienceFilterExpression]): + A list of Audience filter expressions. + """ + + filter_expressions: MutableSequence['AudienceFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AudienceFilterExpression', + ) + + +class AudienceSimpleFilter(proto.Message): + r"""Defines a simple filter that a user must satisfy to be a + member of the Audience. + + Attributes: + scope (google.analytics.admin_v1alpha.types.AudienceFilterScope): + Required. Immutable. Specifies the scope for + this filter. + filter_expression (google.analytics.admin_v1alpha.types.AudienceFilterExpression): + Required. Immutable. A logical expression of + Audience dimension, metric, or event filters. + """ + + scope: 'AudienceFilterScope' = proto.Field( + proto.ENUM, + number=1, + enum='AudienceFilterScope', + ) + filter_expression: 'AudienceFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + message='AudienceFilterExpression', + ) + + +class AudienceSequenceFilter(proto.Message): + r"""Defines filters that must occur in a specific order for the + user to be a member of the Audience. + + Attributes: + scope (google.analytics.admin_v1alpha.types.AudienceFilterScope): + Required. Immutable. Specifies the scope for + this filter. + sequence_maximum_duration (google.protobuf.duration_pb2.Duration): + Optional. Defines the time period in which + the whole sequence must occur. + sequence_steps (MutableSequence[google.analytics.admin_v1alpha.types.AudienceSequenceFilter.AudienceSequenceStep]): + Required. An ordered sequence of steps. A + user must complete each step in order to join + the sequence filter. + """ + + class AudienceSequenceStep(proto.Message): + r"""A condition that must occur in the specified step order for + this user to match the sequence. + + Attributes: + scope (google.analytics.admin_v1alpha.types.AudienceFilterScope): + Required. Immutable. Specifies the scope for + this step. + immediately_follows (bool): + Optional. If true, the event satisfying this + step must be the very next event after the event + satisfying the last step. If unset or false, + this step indirectly follows the prior step; for + example, there may be events between the prior + step and this step. It is ignored for the first + step. + constraint_duration (google.protobuf.duration_pb2.Duration): + Optional. When set, this step must be satisfied within the + constraint_duration of the previous step (For example, t[i] + - t[i-1] <= constraint_duration). If not set, there is no + duration requirement (the duration is effectively + unlimited). It is ignored for the first step. + filter_expression (google.analytics.admin_v1alpha.types.AudienceFilterExpression): + Required. Immutable. A logical expression of + Audience dimension, metric, or event filters in + each step. + """ + + scope: 'AudienceFilterScope' = proto.Field( + proto.ENUM, + number=1, + enum='AudienceFilterScope', + ) + immediately_follows: bool = proto.Field( + proto.BOOL, + number=2, + ) + constraint_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + filter_expression: 'AudienceFilterExpression' = proto.Field( + proto.MESSAGE, + number=4, + message='AudienceFilterExpression', + ) + + scope: 'AudienceFilterScope' = proto.Field( + proto.ENUM, + number=1, + enum='AudienceFilterScope', + ) + sequence_maximum_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + sequence_steps: MutableSequence[AudienceSequenceStep] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AudienceSequenceStep, + ) + + +class AudienceFilterClause(proto.Message): + r"""A clause for defining either a simple or sequence filter. A + filter can be inclusive (For example, users satisfying the + filter clause are included in the Audience) or exclusive (For + example, users satisfying the filter clause are excluded from + the Audience). + + 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: + simple_filter (google.analytics.admin_v1alpha.types.AudienceSimpleFilter): + A simple filter that a user must satisfy to + be a member of the Audience. + + This field is a member of `oneof`_ ``filter``. + sequence_filter (google.analytics.admin_v1alpha.types.AudienceSequenceFilter): + Filters that must occur in a specific order + for the user to be a member of the Audience. + + This field is a member of `oneof`_ ``filter``. + clause_type (google.analytics.admin_v1alpha.types.AudienceFilterClause.AudienceClauseType): + Required. Specifies whether this is an + include or exclude filter clause. + """ + class AudienceClauseType(proto.Enum): + r"""Specifies whether this is an include or exclude filter + clause. + + Values: + AUDIENCE_CLAUSE_TYPE_UNSPECIFIED (0): + Unspecified clause type. + INCLUDE (1): + Users will be included in the Audience if the + filter clause is met. + EXCLUDE (2): + Users will be excluded from the Audience if + the filter clause is met. + """ + AUDIENCE_CLAUSE_TYPE_UNSPECIFIED = 0 + INCLUDE = 1 + EXCLUDE = 2 + + simple_filter: 'AudienceSimpleFilter' = proto.Field( + proto.MESSAGE, + number=2, + oneof='filter', + message='AudienceSimpleFilter', + ) + sequence_filter: 'AudienceSequenceFilter' = proto.Field( + proto.MESSAGE, + number=3, + oneof='filter', + message='AudienceSequenceFilter', + ) + clause_type: AudienceClauseType = proto.Field( + proto.ENUM, + number=1, + enum=AudienceClauseType, + ) + + +class AudienceEventTrigger(proto.Message): + r"""Specifies an event to log when a user joins the Audience. + + Attributes: + event_name (str): + Required. The event name that will be logged. + log_condition (google.analytics.admin_v1alpha.types.AudienceEventTrigger.LogCondition): + Required. When to log the event. + """ + class LogCondition(proto.Enum): + r"""Determines when to log the event. + + Values: + LOG_CONDITION_UNSPECIFIED (0): + Log condition is not specified. + AUDIENCE_JOINED (1): + The event should be logged only when a user + is joined. + AUDIENCE_MEMBERSHIP_RENEWED (2): + The event should be logged whenever the + Audience condition is met, even if the user is + already a member of the Audience. + """ + LOG_CONDITION_UNSPECIFIED = 0 + AUDIENCE_JOINED = 1 + AUDIENCE_MEMBERSHIP_RENEWED = 2 + + event_name: str = proto.Field( + proto.STRING, + number=1, + ) + log_condition: LogCondition = proto.Field( + proto.ENUM, + number=2, + enum=LogCondition, + ) + + +class Audience(proto.Message): + r"""A resource message representing a GA4 Audience. + + Attributes: + name (str): + Output only. The resource name for this + Audience resource. Format: + properties/{propertyId}/audiences/{audienceId} + display_name (str): + Required. The display name of the Audience. + description (str): + Required. The description of the Audience. + membership_duration_days (int): + Required. Immutable. The duration a user + should stay in an Audience. It cannot be set to + more than 540 days. + ads_personalization_enabled (bool): + Output only. It is automatically set by GA to + false if this is an NPA Audience and is excluded + from ads personalization. + event_trigger (google.analytics.admin_v1alpha.types.AudienceEventTrigger): + Optional. Specifies an event to log when a + user joins the Audience. If not set, no event is + logged when a user joins the Audience. + exclusion_duration_mode (google.analytics.admin_v1alpha.types.Audience.AudienceExclusionDurationMode): + Immutable. Specifies how long an exclusion + lasts for users that meet the exclusion filter. + It is applied to all EXCLUDE filter clauses and + is ignored when there is no EXCLUDE filter + clause in the Audience. + filter_clauses (MutableSequence[google.analytics.admin_v1alpha.types.AudienceFilterClause]): + Required. Immutable. Unordered list. Filter + clauses that define the Audience. All clauses + will be AND’ed together. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the Audience was + created. + """ + class AudienceExclusionDurationMode(proto.Enum): + r"""Specifies how long an exclusion lasts for users that meet the + exclusion filter. + + Values: + AUDIENCE_EXCLUSION_DURATION_MODE_UNSPECIFIED (0): + Not specified. + EXCLUDE_TEMPORARILY (1): + Exclude users from the Audience during + periods when they meet the filter clause. + EXCLUDE_PERMANENTLY (2): + Exclude users from the Audience if they've + ever met the filter clause. + """ + AUDIENCE_EXCLUSION_DURATION_MODE_UNSPECIFIED = 0 + EXCLUDE_TEMPORARILY = 1 + EXCLUDE_PERMANENTLY = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + membership_duration_days: int = proto.Field( + proto.INT32, + number=4, + ) + ads_personalization_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + event_trigger: 'AudienceEventTrigger' = proto.Field( + proto.MESSAGE, + number=6, + message='AudienceEventTrigger', + ) + exclusion_duration_mode: AudienceExclusionDurationMode = proto.Field( + proto.ENUM, + number=7, + enum=AudienceExclusionDurationMode, + ) + filter_clauses: MutableSequence['AudienceFilterClause'] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message='AudienceFilterClause', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/channel_group.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/channel_group.py new file mode 100644 index 000000000000..3f31394fe433 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/channel_group.py @@ -0,0 +1,307 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin.v1alpha', + manifest={ + 'ChannelGroupFilter', + 'ChannelGroupFilterExpression', + 'ChannelGroupFilterExpressionList', + 'GroupingRule', + 'ChannelGroup', + }, +) + + +class ChannelGroupFilter(proto.Message): + r"""A specific filter for a single dimension. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_filter (google.analytics.admin_v1alpha.types.ChannelGroupFilter.StringFilter): + A filter for a string-type dimension that + matches a particular pattern. + + This field is a member of `oneof`_ ``value_filter``. + in_list_filter (google.analytics.admin_v1alpha.types.ChannelGroupFilter.InListFilter): + A filter for a string dimension that matches + a particular list of options. + + This field is a member of `oneof`_ ``value_filter``. + field_name (str): + Required. Immutable. The dimension name to + filter. + """ + + class StringFilter(proto.Message): + r"""Filter where the field value is a String. The match is case + insensitive. + + Attributes: + match_type (google.analytics.admin_v1alpha.types.ChannelGroupFilter.StringFilter.MatchType): + Required. The match type for the string + filter. + value (str): + Required. The string value to be matched + against. + """ + class MatchType(proto.Enum): + r"""How the filter will be used to determine a match. + + Values: + MATCH_TYPE_UNSPECIFIED (0): + Default match type. + EXACT (1): + Exact match of the string value. + BEGINS_WITH (2): + Begins with the string value. + ENDS_WITH (3): + Ends with the string value. + CONTAINS (4): + Contains the string value. + FULL_REGEXP (5): + Full regular expression match with the string + value. + PARTIAL_REGEXP (6): + Partial regular expression match with the + string value. + """ + MATCH_TYPE_UNSPECIFIED = 0 + EXACT = 1 + BEGINS_WITH = 2 + ENDS_WITH = 3 + CONTAINS = 4 + FULL_REGEXP = 5 + PARTIAL_REGEXP = 6 + + match_type: 'ChannelGroupFilter.StringFilter.MatchType' = proto.Field( + proto.ENUM, + number=1, + enum='ChannelGroupFilter.StringFilter.MatchType', + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + class InListFilter(proto.Message): + r"""A filter for a string dimension that matches a particular + list of options. The match is case insensitive. + + Attributes: + values (MutableSequence[str]): + Required. The list of possible string values + to match against. Must be non-empty. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + string_filter: StringFilter = proto.Field( + proto.MESSAGE, + number=2, + oneof='value_filter', + message=StringFilter, + ) + in_list_filter: InListFilter = proto.Field( + proto.MESSAGE, + number=3, + oneof='value_filter', + message=InListFilter, + ) + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ChannelGroupFilterExpression(proto.Message): + r"""A logical expression of Channel Group dimension filters. + + 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: + and_group (google.analytics.admin_v1alpha.types.ChannelGroupFilterExpressionList): + A list of expressions to be AND’ed together. It can only + contain ChannelGroupFilterExpressions with or_group. This + must be set for the top level ChannelGroupFilterExpression. + + This field is a member of `oneof`_ ``expr``. + or_group (google.analytics.admin_v1alpha.types.ChannelGroupFilterExpressionList): + A list of expressions to OR’ed together. It cannot contain + ChannelGroupFilterExpressions with and_group or or_group. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.admin_v1alpha.types.ChannelGroupFilterExpression): + A filter expression to be NOT'ed (that is inverted, + complemented). It can only include a + dimension_or_metric_filter. This cannot be set on the top + level ChannelGroupFilterExpression. + + This field is a member of `oneof`_ ``expr``. + filter (google.analytics.admin_v1alpha.types.ChannelGroupFilter): + A filter on a single dimension. This cannot + be set on the top level + ChannelGroupFilterExpression. + + This field is a member of `oneof`_ ``expr``. + """ + + and_group: 'ChannelGroupFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='ChannelGroupFilterExpressionList', + ) + or_group: 'ChannelGroupFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='ChannelGroupFilterExpressionList', + ) + not_expression: 'ChannelGroupFilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='ChannelGroupFilterExpression', + ) + filter: 'ChannelGroupFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='expr', + message='ChannelGroupFilter', + ) + + +class ChannelGroupFilterExpressionList(proto.Message): + r"""A list of Channel Group filter expressions. + + Attributes: + filter_expressions (MutableSequence[google.analytics.admin_v1alpha.types.ChannelGroupFilterExpression]): + A list of Channel Group filter expressions. + """ + + filter_expressions: MutableSequence['ChannelGroupFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ChannelGroupFilterExpression', + ) + + +class GroupingRule(proto.Message): + r"""The rules that govern how traffic is grouped into one + channel. + + Attributes: + display_name (str): + Required. Customer defined display name for + the channel. + expression (google.analytics.admin_v1alpha.types.ChannelGroupFilterExpression): + Required. The Filter Expression that defines + the Grouping Rule. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + expression: 'ChannelGroupFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + message='ChannelGroupFilterExpression', + ) + + +class ChannelGroup(proto.Message): + r"""A resource message representing a Channel Group. + + Attributes: + name (str): + Output only. The resource name for this Channel Group + resource. Format: + properties/{property}/channelGroups/{channel_group} + display_name (str): + Required. The display name of the Channel + Group. Max length of 80 characters. + description (str): + The description of the Channel Group. Max + length of 256 characters. + grouping_rule (MutableSequence[google.analytics.admin_v1alpha.types.GroupingRule]): + Required. The grouping rules of channels. + Maximum number of rules is 50. + system_defined (bool): + Output only. If true, then this channel group + is the Default Channel Group predefined by + Google Analytics. Display name and grouping + rules cannot be updated for this channel group. + primary (bool): + Optional. If true, this channel group will be used as the + default channel group for reports. Only one channel group + can be set as ``primary`` at any time. If the ``primary`` + field gets set on a channel group, it will get unset on the + previous primary channel group. + + The Google Analytics predefined channel group is the primary + by default. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + grouping_rule: MutableSequence['GroupingRule'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='GroupingRule', + ) + system_defined: bool = proto.Field( + proto.BOOL, + number=5, + ) + primary: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/event_create_and_edit.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/event_create_and_edit.py new file mode 100644 index 000000000000..d1963ca3350d --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/event_create_and_edit.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin.v1alpha', + manifest={ + 'ParameterMutation', + 'EventCreateRule', + 'EventEditRule', + 'MatchingCondition', + }, +) + + +class ParameterMutation(proto.Message): + r"""Defines an event parameter to mutate. + + Attributes: + parameter (str): + Required. The name of the parameter to mutate. This value + must: + + - be less than 40 characters. + - be unique across across all mutations within the rule + - consist only of letters, digits or \_ (underscores) For + event edit rules, the name may also be set to + 'event_name' to modify the event_name in place. + parameter_value (str): + Required. The value mutation to perform. + + - Must be less than 100 characters. + - To specify a constant value for the param, use the + value's string. + - To copy value from another parameter, use syntax like + "[[other_parameter]]" For more details, see this `help + center + article `__. + """ + + parameter: str = proto.Field( + proto.STRING, + number=1, + ) + parameter_value: str = proto.Field( + proto.STRING, + number=2, + ) + + +class EventCreateRule(proto.Message): + r"""An Event Create Rule defines conditions that will trigger the + creation of an entirely new event based upon matched criteria of + a source event. Additional mutations of the parameters from the + source event can be defined. + + Unlike Event Edit rules, Event Creation Rules have no defined + order. They will all be run independently. + + Event Edit and Event Create rules can't be used to modify an + event created from an Event Create rule. + + Attributes: + name (str): + Output only. Resource name for this EventCreateRule + resource. Format: + properties/{property}/dataStreams/{data_stream}/eventCreateRules/{event_create_rule} + destination_event (str): + Required. The name of the new event to be created. + + This value must: + + - be less than 40 characters + - consist only of letters, digits or \_ (underscores) + - start with a letter + event_conditions (MutableSequence[google.analytics.admin_v1alpha.types.MatchingCondition]): + Required. Must have at least one condition, + and can have up to 10 max. Conditions on the + source event must match for this rule to be + applied. + source_copy_parameters (bool): + If true, the source parameters are copied to + the new event. If false, or unset, all + non-internal parameters are not copied from the + source event. Parameter mutations are applied + after the parameters have been copied. + parameter_mutations (MutableSequence[google.analytics.admin_v1alpha.types.ParameterMutation]): + Parameter mutations define parameter behavior + on the new event, and are applied in order. + A maximum of 20 mutations can be applied. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + destination_event: str = proto.Field( + proto.STRING, + number=2, + ) + event_conditions: MutableSequence['MatchingCondition'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='MatchingCondition', + ) + source_copy_parameters: bool = proto.Field( + proto.BOOL, + number=4, + ) + parameter_mutations: MutableSequence['ParameterMutation'] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message='ParameterMutation', + ) + + +class EventEditRule(proto.Message): + r"""An Event Edit Rule defines conditions that will trigger the + creation of an entirely new event based upon matched criteria of + a source event. Additional mutations of the parameters from the + source event can be defined. + + Unlike Event Create rules, Event Edit Rules are applied in their + defined order. + + Event Edit rules can't be used to modify an event created from + an Event Create rule. + + Attributes: + name (str): + Identifier. Resource name for this EventEditRule resource. + Format: + properties/{property}/dataStreams/{data_stream}/eventEditRules/{event_edit_rule} + display_name (str): + Required. The display name of this event edit + rule. Maximum of 255 characters. + event_conditions (MutableSequence[google.analytics.admin_v1alpha.types.MatchingCondition]): + Required. Conditions on the source event must + match for this rule to be applied. Must have at + least one condition, and can have up to 10 max. + parameter_mutations (MutableSequence[google.analytics.admin_v1alpha.types.ParameterMutation]): + Required. Parameter mutations define + parameter behavior on the new event, and are + applied in order. A maximum of 20 mutations can + be applied. + processing_order (int): + Output only. The order for which this rule + will be processed. Rules with an order value + lower than this will be processed before this + rule, rules with an order value higher than this + will be processed after this rule. New event + edit rules will be assigned an order value at + the end of the order. + + This value does not apply to event create rules. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + event_conditions: MutableSequence['MatchingCondition'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='MatchingCondition', + ) + parameter_mutations: MutableSequence['ParameterMutation'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='ParameterMutation', + ) + processing_order: int = proto.Field( + proto.INT64, + number=5, + ) + + +class MatchingCondition(proto.Message): + r"""Defines a condition for when an Event Edit or Event Creation + rule applies to an event. + + Attributes: + field (str): + Required. The name of the field that is compared against for + the condition. If 'event_name' is specified this condition + will apply to the name of the event. Otherwise the condition + will apply to a parameter with the specified name. + + This value cannot contain spaces. + comparison_type (google.analytics.admin_v1alpha.types.MatchingCondition.ComparisonType): + Required. The type of comparison to be + applied to the value. + value (str): + Required. The value being compared against + for this condition. The runtime implementation + may perform type coercion of this value to + evaluate this condition based on the type of the + parameter value. + negated (bool): + Whether or not the result of the comparison should be + negated. For example, if ``negated`` is true, then 'equals' + comparisons would function as 'not equals'. + """ + class ComparisonType(proto.Enum): + r"""Comparison type for matching condition + + Values: + COMPARISON_TYPE_UNSPECIFIED (0): + Unknown + EQUALS (1): + Equals, case sensitive + EQUALS_CASE_INSENSITIVE (2): + Equals, case insensitive + CONTAINS (3): + Contains, case sensitive + CONTAINS_CASE_INSENSITIVE (4): + Contains, case insensitive + STARTS_WITH (5): + Starts with, case sensitive + STARTS_WITH_CASE_INSENSITIVE (6): + Starts with, case insensitive + ENDS_WITH (7): + Ends with, case sensitive + ENDS_WITH_CASE_INSENSITIVE (8): + Ends with, case insensitive + GREATER_THAN (9): + Greater than + GREATER_THAN_OR_EQUAL (10): + Greater than or equal + LESS_THAN (11): + Less than + LESS_THAN_OR_EQUAL (12): + Less than or equal + REGULAR_EXPRESSION (13): + regular expression. Only supported for web + streams. + REGULAR_EXPRESSION_CASE_INSENSITIVE (14): + regular expression, case insensitive. Only + supported for web streams. + """ + COMPARISON_TYPE_UNSPECIFIED = 0 + EQUALS = 1 + EQUALS_CASE_INSENSITIVE = 2 + CONTAINS = 3 + CONTAINS_CASE_INSENSITIVE = 4 + STARTS_WITH = 5 + STARTS_WITH_CASE_INSENSITIVE = 6 + ENDS_WITH = 7 + ENDS_WITH_CASE_INSENSITIVE = 8 + GREATER_THAN = 9 + GREATER_THAN_OR_EQUAL = 10 + LESS_THAN = 11 + LESS_THAN_OR_EQUAL = 12 + REGULAR_EXPRESSION = 13 + REGULAR_EXPRESSION_CASE_INSENSITIVE = 14 + + field: str = proto.Field( + proto.STRING, + number=1, + ) + comparison_type: ComparisonType = proto.Field( + proto.ENUM, + number=2, + enum=ComparisonType, + ) + value: str = proto.Field( + proto.STRING, + number=3, + ) + negated: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/expanded_data_set.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/expanded_data_set.py new file mode 100644 index 000000000000..1068b7268b9d --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/expanded_data_set.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin.v1alpha', + manifest={ + 'ExpandedDataSetFilter', + 'ExpandedDataSetFilterExpression', + 'ExpandedDataSetFilterExpressionList', + 'ExpandedDataSet', + }, +) + + +class ExpandedDataSetFilter(proto.Message): + r"""A specific filter for a single dimension + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_filter (google.analytics.admin_v1alpha.types.ExpandedDataSetFilter.StringFilter): + A filter for a string-type dimension that + matches a particular pattern. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.admin_v1alpha.types.ExpandedDataSetFilter.InListFilter): + A filter for a string dimension that matches + a particular list of options. + + This field is a member of `oneof`_ ``one_filter``. + field_name (str): + Required. The dimension name to filter. + """ + + class StringFilter(proto.Message): + r"""A filter for a string-type dimension that matches a + particular pattern. + + Attributes: + match_type (google.analytics.admin_v1alpha.types.ExpandedDataSetFilter.StringFilter.MatchType): + Required. The match type for the string + filter. + value (str): + Required. The string value to be matched + against. + case_sensitive (bool): + Optional. If true, the match is case-sensitive. If false, + the match is case-insensitive. Must be true when match_type + is EXACT. Must be false when match_type is CONTAINS. + """ + class MatchType(proto.Enum): + r"""The match type for the string filter. + + Values: + MATCH_TYPE_UNSPECIFIED (0): + Unspecified + EXACT (1): + Exact match of the string value. + CONTAINS (2): + Contains the string value. + """ + MATCH_TYPE_UNSPECIFIED = 0 + EXACT = 1 + CONTAINS = 2 + + match_type: 'ExpandedDataSetFilter.StringFilter.MatchType' = proto.Field( + proto.ENUM, + number=1, + enum='ExpandedDataSetFilter.StringFilter.MatchType', + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class InListFilter(proto.Message): + r"""A filter for a string dimension that matches a particular + list of options. + + Attributes: + values (MutableSequence[str]): + Required. The list of possible string values + to match against. Must be non-empty. + case_sensitive (bool): + Optional. If true, the match is + case-sensitive. If false, the match is + case-insensitive. Must be true. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=2, + ) + + string_filter: StringFilter = proto.Field( + proto.MESSAGE, + number=2, + oneof='one_filter', + message=StringFilter, + ) + in_list_filter: InListFilter = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_filter', + message=InListFilter, + ) + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ExpandedDataSetFilterExpression(proto.Message): + r"""A logical expression of EnhancedDataSet dimension filters. + + 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: + and_group (google.analytics.admin_v1alpha.types.ExpandedDataSetFilterExpressionList): + A list of expressions to be AND’ed together. It must contain + a ExpandedDataSetFilterExpression with either not_expression + or dimension_filter. This must be set for the top level + ExpandedDataSetFilterExpression. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.admin_v1alpha.types.ExpandedDataSetFilterExpression): + A filter expression to be NOT'ed (that is, inverted, + complemented). It must include a dimension_filter. This + cannot be set on the top level + ExpandedDataSetFilterExpression. + + This field is a member of `oneof`_ ``expr``. + filter (google.analytics.admin_v1alpha.types.ExpandedDataSetFilter): + A filter on a single dimension. This cannot + be set on the top level + ExpandedDataSetFilterExpression. + + This field is a member of `oneof`_ ``expr``. + """ + + and_group: 'ExpandedDataSetFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='ExpandedDataSetFilterExpressionList', + ) + not_expression: 'ExpandedDataSetFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='ExpandedDataSetFilterExpression', + ) + filter: 'ExpandedDataSetFilter' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='ExpandedDataSetFilter', + ) + + +class ExpandedDataSetFilterExpressionList(proto.Message): + r"""A list of ExpandedDataSet filter expressions. + + Attributes: + filter_expressions (MutableSequence[google.analytics.admin_v1alpha.types.ExpandedDataSetFilterExpression]): + A list of ExpandedDataSet filter expressions. + """ + + filter_expressions: MutableSequence['ExpandedDataSetFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ExpandedDataSetFilterExpression', + ) + + +class ExpandedDataSet(proto.Message): + r"""A resource message representing a GA4 ExpandedDataSet. + + Attributes: + name (str): + Output only. The resource name for this ExpandedDataSet + resource. Format: + properties/{property_id}/expandedDataSets/{expanded_data_set} + display_name (str): + Required. The display name of the + ExpandedDataSet. Max 200 chars. + description (str): + Optional. The description of the + ExpandedDataSet. Max 50 chars. + dimension_names (MutableSequence[str]): + Immutable. The list of dimensions included in the + ExpandedDataSet. See the `API + Dimensions `__ + for the list of dimension names. + metric_names (MutableSequence[str]): + Immutable. The list of metrics included in the + ExpandedDataSet. See the `API + Metrics `__ + for the list of dimension names. + dimension_filter_expression (google.analytics.admin_v1alpha.types.ExpandedDataSetFilterExpression): + Immutable. A logical expression of ExpandedDataSet filters + applied to dimension included in the ExpandedDataSet. This + filter is used to reduce the number of rows and thus the + chance of encountering ``other`` row. + data_collection_start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when expanded data set + began (or will begin) collecing data. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + dimension_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + metric_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + dimension_filter_expression: 'ExpandedDataSetFilterExpression' = proto.Field( + proto.MESSAGE, + number=6, + message='ExpandedDataSetFilterExpression', + ) + data_collection_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/resources.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/resources.py new file mode 100644 index 000000000000..7a00ea520469 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/resources.py @@ -0,0 +1,3245 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1alpha.types import audience as gaa_audience +from google.analytics.admin_v1alpha.types import channel_group as gaa_channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set as gaa_expanded_data_set +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.analytics.admin.v1alpha', + manifest={ + 'IndustryCategory', + 'ServiceLevel', + 'ActorType', + 'ActionType', + 'ChangeHistoryResourceType', + 'GoogleSignalsState', + 'GoogleSignalsConsent', + 'LinkProposalInitiatingProduct', + 'LinkProposalState', + 'PropertyType', + 'CoarseValue', + 'Account', + 'Property', + 'DataStream', + 'FirebaseLink', + 'GlobalSiteTag', + 'GoogleAdsLink', + 'DataSharingSettings', + 'AccountSummary', + 'PropertySummary', + 'MeasurementProtocolSecret', + 'SKAdNetworkConversionValueSchema', + 'PostbackWindow', + 'ConversionValues', + 'EventMapping', + 'ChangeHistoryEvent', + 'ChangeHistoryChange', + 'DisplayVideo360AdvertiserLink', + 'DisplayVideo360AdvertiserLinkProposal', + 'SearchAds360Link', + 'LinkProposalStatusDetails', + 'ConversionEvent', + 'KeyEvent', + 'GoogleSignalsSettings', + 'CustomDimension', + 'CustomMetric', + 'CalculatedMetric', + 'DataRetentionSettings', + 'AttributionSettings', + 'AccessBinding', + 'BigQueryLink', + 'EnhancedMeasurementSettings', + 'ConnectedSiteTag', + 'DataRedactionSettings', + 'AdSenseLink', + 'RollupPropertySourceLink', + }, +) + + +class IndustryCategory(proto.Enum): + r"""The category selected for this property, used for industry + benchmarking. + + Values: + INDUSTRY_CATEGORY_UNSPECIFIED (0): + Industry category unspecified + AUTOMOTIVE (1): + Automotive + BUSINESS_AND_INDUSTRIAL_MARKETS (2): + Business and industrial markets + FINANCE (3): + Finance + HEALTHCARE (4): + Healthcare + TECHNOLOGY (5): + Technology + TRAVEL (6): + Travel + OTHER (7): + Other + ARTS_AND_ENTERTAINMENT (8): + Arts and entertainment + BEAUTY_AND_FITNESS (9): + Beauty and fitness + BOOKS_AND_LITERATURE (10): + Books and literature + FOOD_AND_DRINK (11): + Food and drink + GAMES (12): + Games + HOBBIES_AND_LEISURE (13): + Hobbies and leisure + HOME_AND_GARDEN (14): + Home and garden + INTERNET_AND_TELECOM (15): + Internet and telecom + LAW_AND_GOVERNMENT (16): + Law and government + NEWS (17): + News + ONLINE_COMMUNITIES (18): + Online communities + PEOPLE_AND_SOCIETY (19): + People and society + PETS_AND_ANIMALS (20): + Pets and animals + REAL_ESTATE (21): + Real estate + REFERENCE (22): + Reference + SCIENCE (23): + Science + SPORTS (24): + Sports + JOBS_AND_EDUCATION (25): + Jobs and education + SHOPPING (26): + Shopping + """ + INDUSTRY_CATEGORY_UNSPECIFIED = 0 + AUTOMOTIVE = 1 + BUSINESS_AND_INDUSTRIAL_MARKETS = 2 + FINANCE = 3 + HEALTHCARE = 4 + TECHNOLOGY = 5 + TRAVEL = 6 + OTHER = 7 + ARTS_AND_ENTERTAINMENT = 8 + BEAUTY_AND_FITNESS = 9 + BOOKS_AND_LITERATURE = 10 + FOOD_AND_DRINK = 11 + GAMES = 12 + HOBBIES_AND_LEISURE = 13 + HOME_AND_GARDEN = 14 + INTERNET_AND_TELECOM = 15 + LAW_AND_GOVERNMENT = 16 + NEWS = 17 + ONLINE_COMMUNITIES = 18 + PEOPLE_AND_SOCIETY = 19 + PETS_AND_ANIMALS = 20 + REAL_ESTATE = 21 + REFERENCE = 22 + SCIENCE = 23 + SPORTS = 24 + JOBS_AND_EDUCATION = 25 + SHOPPING = 26 + + +class ServiceLevel(proto.Enum): + r"""Various levels of service for Google Analytics. + + Values: + SERVICE_LEVEL_UNSPECIFIED (0): + Service level not specified or invalid. + GOOGLE_ANALYTICS_STANDARD (1): + The standard version of Google Analytics. + GOOGLE_ANALYTICS_360 (2): + The paid, premium version of Google + Analytics. + """ + SERVICE_LEVEL_UNSPECIFIED = 0 + GOOGLE_ANALYTICS_STANDARD = 1 + GOOGLE_ANALYTICS_360 = 2 + + +class ActorType(proto.Enum): + r"""Different kinds of actors that can make changes to Google + Analytics resources. + + Values: + ACTOR_TYPE_UNSPECIFIED (0): + Unknown or unspecified actor type. + USER (1): + Changes made by the user specified in actor_email. + SYSTEM (2): + Changes made by the Google Analytics system. + SUPPORT (3): + Changes made by Google Analytics support team + staff. + """ + ACTOR_TYPE_UNSPECIFIED = 0 + USER = 1 + SYSTEM = 2 + SUPPORT = 3 + + +class ActionType(proto.Enum): + r"""Types of actions that may change a resource. + + Values: + ACTION_TYPE_UNSPECIFIED (0): + Action type unknown or not specified. + CREATED (1): + Resource was created in this change. + UPDATED (2): + Resource was updated in this change. + DELETED (3): + Resource was deleted in this change. + """ + ACTION_TYPE_UNSPECIFIED = 0 + CREATED = 1 + UPDATED = 2 + DELETED = 3 + + +class ChangeHistoryResourceType(proto.Enum): + r"""Types of resources whose changes may be returned from change + history. + + Values: + CHANGE_HISTORY_RESOURCE_TYPE_UNSPECIFIED (0): + Resource type unknown or not specified. + ACCOUNT (1): + Account resource + PROPERTY (2): + Property resource + FIREBASE_LINK (6): + FirebaseLink resource + GOOGLE_ADS_LINK (7): + GoogleAdsLink resource + GOOGLE_SIGNALS_SETTINGS (8): + GoogleSignalsSettings resource + CONVERSION_EVENT (9): + ConversionEvent resource + MEASUREMENT_PROTOCOL_SECRET (10): + MeasurementProtocolSecret resource + CUSTOM_DIMENSION (11): + CustomDimension resource + CUSTOM_METRIC (12): + CustomMetric resource + DATA_RETENTION_SETTINGS (13): + DataRetentionSettings resource + DISPLAY_VIDEO_360_ADVERTISER_LINK (14): + DisplayVideo360AdvertiserLink resource + DISPLAY_VIDEO_360_ADVERTISER_LINK_PROPOSAL (15): + DisplayVideo360AdvertiserLinkProposal + resource + SEARCH_ADS_360_LINK (16): + SearchAds360Link resource + DATA_STREAM (18): + DataStream resource + ATTRIBUTION_SETTINGS (20): + AttributionSettings resource + EXPANDED_DATA_SET (21): + ExpandedDataSet resource + CHANNEL_GROUP (22): + ChannelGroup resource + BIGQUERY_LINK (23): + BigQuery link resource + ENHANCED_MEASUREMENT_SETTINGS (24): + EnhancedMeasurementSettings resource + DATA_REDACTION_SETTINGS (25): + DataRedactionSettings resource + SKADNETWORK_CONVERSION_VALUE_SCHEMA (26): + SKAdNetworkConversionValueSchema resource + ADSENSE_LINK (27): + AdSenseLink resource + AUDIENCE (28): + Audience resource + EVENT_CREATE_RULE (29): + EventCreateRule resource + CALCULATED_METRIC (31): + CalculatedMetric resource + """ + CHANGE_HISTORY_RESOURCE_TYPE_UNSPECIFIED = 0 + ACCOUNT = 1 + PROPERTY = 2 + FIREBASE_LINK = 6 + GOOGLE_ADS_LINK = 7 + GOOGLE_SIGNALS_SETTINGS = 8 + CONVERSION_EVENT = 9 + MEASUREMENT_PROTOCOL_SECRET = 10 + CUSTOM_DIMENSION = 11 + CUSTOM_METRIC = 12 + DATA_RETENTION_SETTINGS = 13 + DISPLAY_VIDEO_360_ADVERTISER_LINK = 14 + DISPLAY_VIDEO_360_ADVERTISER_LINK_PROPOSAL = 15 + SEARCH_ADS_360_LINK = 16 + DATA_STREAM = 18 + ATTRIBUTION_SETTINGS = 20 + EXPANDED_DATA_SET = 21 + CHANNEL_GROUP = 22 + BIGQUERY_LINK = 23 + ENHANCED_MEASUREMENT_SETTINGS = 24 + DATA_REDACTION_SETTINGS = 25 + SKADNETWORK_CONVERSION_VALUE_SCHEMA = 26 + ADSENSE_LINK = 27 + AUDIENCE = 28 + EVENT_CREATE_RULE = 29 + CALCULATED_METRIC = 31 + + +class GoogleSignalsState(proto.Enum): + r"""Status of the Google Signals settings. + + Values: + GOOGLE_SIGNALS_STATE_UNSPECIFIED (0): + Google Signals status defaults to + GOOGLE_SIGNALS_STATE_UNSPECIFIED to represent that the user + has not made an explicit choice. + GOOGLE_SIGNALS_ENABLED (1): + Google Signals is enabled. + GOOGLE_SIGNALS_DISABLED (2): + Google Signals is disabled. + """ + GOOGLE_SIGNALS_STATE_UNSPECIFIED = 0 + GOOGLE_SIGNALS_ENABLED = 1 + GOOGLE_SIGNALS_DISABLED = 2 + + +class GoogleSignalsConsent(proto.Enum): + r"""Consent field of the Google Signals settings. + + Values: + GOOGLE_SIGNALS_CONSENT_UNSPECIFIED (0): + Google Signals consent value defaults to + GOOGLE_SIGNALS_CONSENT_UNSPECIFIED. This will be treated as + GOOGLE_SIGNALS_CONSENT_NOT_CONSENTED. + GOOGLE_SIGNALS_CONSENT_CONSENTED (2): + Terms of service have been accepted + GOOGLE_SIGNALS_CONSENT_NOT_CONSENTED (1): + Terms of service have not been accepted + """ + GOOGLE_SIGNALS_CONSENT_UNSPECIFIED = 0 + GOOGLE_SIGNALS_CONSENT_CONSENTED = 2 + GOOGLE_SIGNALS_CONSENT_NOT_CONSENTED = 1 + + +class LinkProposalInitiatingProduct(proto.Enum): + r"""An indication of which product the user initiated a link + proposal from. + + Values: + LINK_PROPOSAL_INITIATING_PRODUCT_UNSPECIFIED (0): + Unspecified product. + GOOGLE_ANALYTICS (1): + This proposal was created by a user from + Google Analytics. + LINKED_PRODUCT (2): + This proposal was created by a user from a + linked product (not Google Analytics). + """ + LINK_PROPOSAL_INITIATING_PRODUCT_UNSPECIFIED = 0 + GOOGLE_ANALYTICS = 1 + LINKED_PRODUCT = 2 + + +class LinkProposalState(proto.Enum): + r"""The state of a link proposal resource. + + Values: + LINK_PROPOSAL_STATE_UNSPECIFIED (0): + Unspecified state + AWAITING_REVIEW_FROM_GOOGLE_ANALYTICS (1): + This proposal is awaiting review from a + Google Analytics user. This proposal will + automatically expire after some time. + AWAITING_REVIEW_FROM_LINKED_PRODUCT (2): + This proposal is awaiting review from a user + of a linked product. This proposal will + automatically expire after some time. + WITHDRAWN (3): + This proposal has been withdrawn by an admin + on the initiating product. This proposal will be + automatically deleted after some time. + DECLINED (4): + This proposal has been declined by an admin + on the receiving product. This proposal will be + automatically deleted after some time. + EXPIRED (5): + This proposal expired due to lack of response + from an admin on the receiving product. This + proposal will be automatically deleted after + some time. + OBSOLETE (6): + This proposal has become obsolete because a + link was directly created to the same external + product resource that this proposal specifies. + This proposal will be automatically deleted + after some time. + """ + LINK_PROPOSAL_STATE_UNSPECIFIED = 0 + AWAITING_REVIEW_FROM_GOOGLE_ANALYTICS = 1 + AWAITING_REVIEW_FROM_LINKED_PRODUCT = 2 + WITHDRAWN = 3 + DECLINED = 4 + EXPIRED = 5 + OBSOLETE = 6 + + +class PropertyType(proto.Enum): + r"""Types of Property resources. + + Values: + PROPERTY_TYPE_UNSPECIFIED (0): + Unknown or unspecified property type + PROPERTY_TYPE_ORDINARY (1): + Ordinary GA4 property + PROPERTY_TYPE_SUBPROPERTY (2): + GA4 subproperty + PROPERTY_TYPE_ROLLUP (3): + GA4 rollup property + """ + PROPERTY_TYPE_UNSPECIFIED = 0 + PROPERTY_TYPE_ORDINARY = 1 + PROPERTY_TYPE_SUBPROPERTY = 2 + PROPERTY_TYPE_ROLLUP = 3 + + +class CoarseValue(proto.Enum): + r"""The coarse conversion value set on the updatePostbackConversionValue + SDK call when a ConversionValues.event_mappings conditions are + satisfied. For more information, see + `SKAdNetwork.CoarseConversionValue `__. + + Values: + COARSE_VALUE_UNSPECIFIED (0): + Coarse value not specified. + COARSE_VALUE_LOW (1): + Coarse value of low. + COARSE_VALUE_MEDIUM (2): + Coarse value of medium. + COARSE_VALUE_HIGH (3): + Coarse value of high. + """ + COARSE_VALUE_UNSPECIFIED = 0 + COARSE_VALUE_LOW = 1 + COARSE_VALUE_MEDIUM = 2 + COARSE_VALUE_HIGH = 3 + + +class Account(proto.Message): + r"""A resource message representing a Google Analytics account. + + Attributes: + name (str): + Output only. Resource name of this account. + Format: accounts/{account} + Example: "accounts/100". + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this account was + originally created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when account payload fields + were last updated. + display_name (str): + Required. Human-readable display name for + this account. + region_code (str): + Country of business. Must be a Unicode CLDR + region code. + deleted (bool): + Output only. Indicates whether this Account + is soft-deleted or not. Deleted accounts are + excluded from List results unless specifically + requested. + gmp_organization (str): + Output only. The URI for a Google Marketing Platform + organization resource. Only set when this account is + connected to a GMP organization. Format: + marketingplatformadmin.googleapis.com/organizations/{org_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + region_code: str = proto.Field( + proto.STRING, + number=5, + ) + deleted: bool = proto.Field( + proto.BOOL, + number=6, + ) + gmp_organization: str = proto.Field( + proto.STRING, + number=7, + ) + + +class Property(proto.Message): + r"""A resource message representing a Google Analytics GA4 + property. + + Attributes: + name (str): + Output only. Resource name of this property. Format: + properties/{property_id} Example: "properties/1000". + property_type (google.analytics.admin_v1alpha.types.PropertyType): + Immutable. The property type for this Property resource. + When creating a property, if the type is + "PROPERTY_TYPE_UNSPECIFIED", then "ORDINARY_PROPERTY" will + be implied. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the entity was + originally created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when entity payload fields + were last updated. + parent (str): + Immutable. Resource name of this property's + logical parent. + Note: The Property-Moving UI can be used to + change the parent. Format: accounts/{account}, + properties/{property} Example: "accounts/100", + "properties/101". + display_name (str): + Required. Human-readable display name for + this property. + The max allowed display name length is 100 + UTF-16 code units. + industry_category (google.analytics.admin_v1alpha.types.IndustryCategory): + Industry associated with this property Example: AUTOMOTIVE, + FOOD_AND_DRINK + time_zone (str): + Required. Reporting Time Zone, used as the day boundary for + reports, regardless of where the data originates. If the + time zone honors DST, Analytics will automatically adjust + for the changes. + + NOTE: Changing the time zone only affects data going + forward, and is not applied retroactively. + + Format: https://www.iana.org/time-zones Example: + "America/Los_Angeles". + currency_code (str): + The currency type used in reports involving monetary values. + + Format: https://en.wikipedia.org/wiki/ISO_4217 Examples: + "USD", "EUR", "JPY". + service_level (google.analytics.admin_v1alpha.types.ServiceLevel): + Output only. The Google Analytics service + level that applies to this property. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. If set, the time at which this + property was trashed. If not set, then this + property is not currently in the trash can. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. If set, the time at which this + trashed property will be permanently deleted. If + not set, then this property is not currently in + the trash can and is not slated to be deleted. + account (str): + Immutable. The resource name of the parent account Format: + accounts/{account_id} Example: "accounts/123". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + property_type: 'PropertyType' = proto.Field( + proto.ENUM, + number=14, + enum='PropertyType', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + industry_category: 'IndustryCategory' = proto.Field( + proto.ENUM, + number=6, + enum='IndustryCategory', + ) + time_zone: str = proto.Field( + proto.STRING, + number=7, + ) + currency_code: str = proto.Field( + proto.STRING, + number=8, + ) + service_level: 'ServiceLevel' = proto.Field( + proto.ENUM, + number=10, + enum='ServiceLevel', + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + account: str = proto.Field( + proto.STRING, + number=13, + ) + + +class DataStream(proto.Message): + r"""A resource message representing a data stream. + + 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: + web_stream_data (google.analytics.admin_v1alpha.types.DataStream.WebStreamData): + Data specific to web streams. Must be populated if type is + WEB_DATA_STREAM. + + This field is a member of `oneof`_ ``stream_data``. + android_app_stream_data (google.analytics.admin_v1alpha.types.DataStream.AndroidAppStreamData): + Data specific to Android app streams. Must be populated if + type is ANDROID_APP_DATA_STREAM. + + This field is a member of `oneof`_ ``stream_data``. + ios_app_stream_data (google.analytics.admin_v1alpha.types.DataStream.IosAppStreamData): + Data specific to iOS app streams. Must be populated if type + is IOS_APP_DATA_STREAM. + + This field is a member of `oneof`_ ``stream_data``. + name (str): + Output only. Resource name of this Data Stream. Format: + properties/{property_id}/dataStreams/{stream_id} Example: + "properties/1000/dataStreams/2000". + type_ (google.analytics.admin_v1alpha.types.DataStream.DataStreamType): + Required. Immutable. The type of this + DataStream resource. + display_name (str): + Human-readable display name for the Data + Stream. + Required for web data streams. + + The max allowed display name length is 255 + UTF-16 code units. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this stream was + originally created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when stream payload fields + were last updated. + """ + class DataStreamType(proto.Enum): + r"""The type of the data stream. + + Values: + DATA_STREAM_TYPE_UNSPECIFIED (0): + Type unknown or not specified. + WEB_DATA_STREAM (1): + Web data stream. + ANDROID_APP_DATA_STREAM (2): + Android app data stream. + IOS_APP_DATA_STREAM (3): + iOS app data stream. + """ + DATA_STREAM_TYPE_UNSPECIFIED = 0 + WEB_DATA_STREAM = 1 + ANDROID_APP_DATA_STREAM = 2 + IOS_APP_DATA_STREAM = 3 + + class WebStreamData(proto.Message): + r"""Data specific to web streams. + + Attributes: + measurement_id (str): + Output only. Analytics Measurement ID. + + Example: "G-1A2BCD345E". + firebase_app_id (str): + Output only. ID of the corresponding web app + in Firebase, if any. This ID can change if the + web app is deleted and recreated. + default_uri (str): + Domain name of the web app being measured, or + empty. Example: "http://www.google.com", + "https://www.google.com". + """ + + measurement_id: str = proto.Field( + proto.STRING, + number=1, + ) + firebase_app_id: str = proto.Field( + proto.STRING, + number=2, + ) + default_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + class AndroidAppStreamData(proto.Message): + r"""Data specific to Android app streams. + + Attributes: + firebase_app_id (str): + Output only. ID of the corresponding Android + app in Firebase, if any. This ID can change if + the Android app is deleted and recreated. + package_name (str): + Immutable. The package name for the app being + measured. Example: "com.example.myandroidapp". + """ + + firebase_app_id: str = proto.Field( + proto.STRING, + number=1, + ) + package_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class IosAppStreamData(proto.Message): + r"""Data specific to iOS app streams. + + Attributes: + firebase_app_id (str): + Output only. ID of the corresponding iOS app + in Firebase, if any. This ID can change if the + iOS app is deleted and recreated. + bundle_id (str): + Required. Immutable. The Apple App Store + Bundle ID for the app Example: + "com.example.myiosapp". + """ + + firebase_app_id: str = proto.Field( + proto.STRING, + number=1, + ) + bundle_id: str = proto.Field( + proto.STRING, + number=2, + ) + + web_stream_data: WebStreamData = proto.Field( + proto.MESSAGE, + number=6, + oneof='stream_data', + message=WebStreamData, + ) + android_app_stream_data: AndroidAppStreamData = proto.Field( + proto.MESSAGE, + number=7, + oneof='stream_data', + message=AndroidAppStreamData, + ) + ios_app_stream_data: IosAppStreamData = proto.Field( + proto.MESSAGE, + number=8, + oneof='stream_data', + message=IosAppStreamData, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: DataStreamType = proto.Field( + proto.ENUM, + number=2, + enum=DataStreamType, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class FirebaseLink(proto.Message): + r"""A link between a GA4 property and a Firebase project. + + Attributes: + name (str): + Output only. Example format: + properties/1234/firebaseLinks/5678 + project (str): + Immutable. Firebase project resource name. When creating a + FirebaseLink, you may provide this resource name using + either a project number or project ID. Once this resource + has been created, returned FirebaseLinks will always have a + project_name that contains a project number. + + Format: 'projects/{project number}' Example: 'projects/1234' + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this FirebaseLink was + originally created. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class GlobalSiteTag(proto.Message): + r"""Read-only resource with the tag for sending data from a + website to a DataStream. Only present for web DataStream + resources. + + Attributes: + name (str): + Output only. Resource name for this GlobalSiteTag resource. + Format: + properties/{property_id}/dataStreams/{stream_id}/globalSiteTag + Example: "properties/123/dataStreams/456/globalSiteTag". + snippet (str): + Immutable. JavaScript code snippet to be + pasted as the first item into the head tag of + every webpage to measure. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + snippet: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GoogleAdsLink(proto.Message): + r"""A link between a GA4 property and a Google Ads account. + + Attributes: + name (str): + Output only. Format: + + properties/{propertyId}/googleAdsLinks/{googleAdsLinkId} + + Note: googleAdsLinkId is not the Google Ads + customer ID. + customer_id (str): + Immutable. Google Ads customer ID. + can_manage_clients (bool): + Output only. If true, this link is for a + Google Ads manager account. + ads_personalization_enabled (google.protobuf.wrappers_pb2.BoolValue): + Enable personalized advertising features with + this integration. Automatically publish my + Google Analytics audience lists and Google + Analytics remarketing events/parameters to the + linked Google Ads account. If this field is not + set on create/update, it will be defaulted to + true. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this link was + originally created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this link was last + updated. + creator_email_address (str): + Output only. Email address of the user that + created the link. An empty string will be + returned if the email address can't be + retrieved. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + customer_id: str = proto.Field( + proto.STRING, + number=3, + ) + can_manage_clients: bool = proto.Field( + proto.BOOL, + number=4, + ) + ads_personalization_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.BoolValue, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + creator_email_address: str = proto.Field( + proto.STRING, + number=9, + ) + + +class DataSharingSettings(proto.Message): + r"""A resource message representing data sharing settings of a + Google Analytics account. + + Attributes: + name (str): + Output only. Resource name. + Format: accounts/{account}/dataSharingSettings + Example: "accounts/1000/dataSharingSettings". + sharing_with_google_support_enabled (bool): + Allows Google support to access the data in + order to help troubleshoot issues. + sharing_with_google_assigned_sales_enabled (bool): + Allows Google sales teams that are assigned + to the customer to access the data in order to + suggest configuration changes to improve + results. Sales team restrictions still apply + when enabled. + sharing_with_google_any_sales_enabled (bool): + Allows any of Google sales to access the data + in order to suggest configuration changes to + improve results. + sharing_with_google_products_enabled (bool): + Allows Google to use the data to improve + other Google products or services. + sharing_with_others_enabled (bool): + Allows Google to share the data anonymously + in aggregate form with others. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + sharing_with_google_support_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + sharing_with_google_assigned_sales_enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + sharing_with_google_any_sales_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + sharing_with_google_products_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + sharing_with_others_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class AccountSummary(proto.Message): + r"""A virtual resource representing an overview of an account and + all its child GA4 properties. + + Attributes: + name (str): + Resource name for this account summary. Format: + accountSummaries/{account_id} Example: + "accountSummaries/1000". + account (str): + Resource name of account referred to by this account summary + Format: accounts/{account_id} Example: "accounts/1000". + display_name (str): + Display name for the account referred to in + this account summary. + property_summaries (MutableSequence[google.analytics.admin_v1alpha.types.PropertySummary]): + List of summaries for child accounts of this + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + property_summaries: MutableSequence['PropertySummary'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='PropertySummary', + ) + + +class PropertySummary(proto.Message): + r"""A virtual resource representing metadata for a GA4 property. + + Attributes: + property (str): + Resource name of property referred to by this property + summary Format: properties/{property_id} Example: + "properties/1000". + display_name (str): + Display name for the property referred to in + this property summary. + property_type (google.analytics.admin_v1alpha.types.PropertyType): + The property's property type. + parent (str): + Resource name of this property's logical + parent. + Note: The Property-Moving UI can be used to + change the parent. Format: accounts/{account}, + properties/{property} Example: "accounts/100", + "properties/200". + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + property_type: 'PropertyType' = proto.Field( + proto.ENUM, + number=3, + enum='PropertyType', + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + + +class MeasurementProtocolSecret(proto.Message): + r"""A secret value used for sending hits to Measurement Protocol. + + Attributes: + name (str): + Output only. Resource name of this secret. + This secret may be a child of any type of + stream. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + display_name (str): + Required. Human-readable display name for + this secret. + secret_value (str): + Output only. The measurement protocol secret value. Pass + this value to the api_secret field of the Measurement + Protocol API when sending hits to this secret's parent + property. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + secret_value: str = proto.Field( + proto.STRING, + number=3, + ) + + +class SKAdNetworkConversionValueSchema(proto.Message): + r"""SKAdNetwork conversion value schema of an iOS stream. + + Attributes: + name (str): + Output only. Resource name of the schema. + This will be child of ONLY an iOS stream, and + there can be at most one such child under an iOS + stream. Format: + + properties/{property}/dataStreams/{dataStream}/sKAdNetworkConversionValueSchema + postback_window_one (google.analytics.admin_v1alpha.types.PostbackWindow): + Required. The conversion value settings for + the first postback window. These differ from + values for postback window two and three in that + they contain a "Fine" grained conversion value + (a numeric value). + + Conversion values for this postback window must + be set. The other windows are optional and may + inherit this window's settings if unset or + disabled. + postback_window_two (google.analytics.admin_v1alpha.types.PostbackWindow): + The conversion value settings for the second postback + window. + + This field should only be configured if there is a need to + define different conversion values for this postback window. + + If enable_postback_window_settings is set to false for this + postback window, the values from postback_window_one will be + used. + postback_window_three (google.analytics.admin_v1alpha.types.PostbackWindow): + The conversion value settings for the third postback window. + + This field should only be set if the user chose to define + different conversion values for this postback window. It is + allowed to configure window 3 without setting window 2. In + case window 1 & 2 settings are set and + enable_postback_window_settings for this postback window is + set to false, the schema will inherit settings from + postback_window_two. + apply_conversion_values (bool): + If enabled, the GA SDK will set conversion + values using this schema definition, and schema + will be exported to any Google Ads accounts + linked to this property. If disabled, the GA SDK + will not automatically set conversion values, + and also the schema will not be exported to Ads. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + postback_window_one: 'PostbackWindow' = proto.Field( + proto.MESSAGE, + number=2, + message='PostbackWindow', + ) + postback_window_two: 'PostbackWindow' = proto.Field( + proto.MESSAGE, + number=3, + message='PostbackWindow', + ) + postback_window_three: 'PostbackWindow' = proto.Field( + proto.MESSAGE, + number=4, + message='PostbackWindow', + ) + apply_conversion_values: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class PostbackWindow(proto.Message): + r"""Settings for a SKAdNetwork conversion postback window. + + Attributes: + conversion_values (MutableSequence[google.analytics.admin_v1alpha.types.ConversionValues]): + Ordering of the repeated field will be used to prioritize + the conversion value settings. Lower indexed entries are + prioritized higher. The first conversion value setting that + evaluates to true will be selected. It must have at least + one entry if enable_postback_window_settings is set to true. + It can have maximum of 128 entries. + postback_window_settings_enabled (bool): + If enable_postback_window_settings is true, + conversion_values must be populated and will be used for + determining when and how to set the Conversion Value on a + client device and exporting schema to linked Ads accounts. + If false, the settings are not used, but are retained in + case they may be used in the future. This must always be + true for postback_window_one. + """ + + conversion_values: MutableSequence['ConversionValues'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='ConversionValues', + ) + postback_window_settings_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class ConversionValues(proto.Message): + r"""Conversion value settings for a postback window for + SKAdNetwork conversion value schema. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + display_name (str): + Display name of the SKAdNetwork conversion + value. The max allowed display name length is 50 + UTF-16 code units. + fine_value (int): + The fine-grained conversion value. This is applicable only + to the first postback window. Its valid values are [0,63], + both inclusive. It must be set for postback window 1, and + must not be set for postback window 2 & 3. This value is not + guaranteed to be unique. + + If the configuration for the first postback window is + re-used for second or third postback windows this field has + no effect. + + This field is a member of `oneof`_ ``_fine_value``. + coarse_value (google.analytics.admin_v1alpha.types.CoarseValue): + Required. A coarse grained conversion value. + + This value is not guaranteed to be unique. + event_mappings (MutableSequence[google.analytics.admin_v1alpha.types.EventMapping]): + Event conditions that must be met for this + Conversion Value to be achieved. The conditions + in this list are ANDed together. It must have + minimum of 1 entry and maximum of 3 entries, if + the postback window is enabled. + lock_enabled (bool): + If true, the SDK should lock to this + conversion value for the current postback + window. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + fine_value: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + coarse_value: 'CoarseValue' = proto.Field( + proto.ENUM, + number=3, + enum='CoarseValue', + ) + event_mappings: MutableSequence['EventMapping'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='EventMapping', + ) + lock_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class EventMapping(proto.Message): + r"""Event setting conditions to match an event. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + event_name (str): + Required. Name of the GA4 event. It must + always be set. The max allowed display name + length is 40 UTF-16 code units. + min_event_count (int): + At least one of the following four min/max + values must be set. The values set will be ANDed + together to qualify an event. The minimum number + of times the event occurred. If not set, minimum + event count won't be checked. + + This field is a member of `oneof`_ ``_min_event_count``. + max_event_count (int): + The maximum number of times the event + occurred. If not set, maximum event count won't + be checked. + + This field is a member of `oneof`_ ``_max_event_count``. + min_event_value (float): + The minimum revenue generated due to the + event. Revenue currency will be defined at the + property level. If not set, minimum event value + won't be checked. + + This field is a member of `oneof`_ ``_min_event_value``. + max_event_value (float): + The maximum revenue generated due to the + event. Revenue currency will be defined at the + property level. If not set, maximum event value + won't be checked. + + This field is a member of `oneof`_ ``_max_event_value``. + """ + + event_name: str = proto.Field( + proto.STRING, + number=1, + ) + min_event_count: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + max_event_count: int = proto.Field( + proto.INT64, + number=3, + optional=True, + ) + min_event_value: float = proto.Field( + proto.DOUBLE, + number=4, + optional=True, + ) + max_event_value: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) + + +class ChangeHistoryEvent(proto.Message): + r"""A set of changes within a Google Analytics account or its + child properties that resulted from the same cause. Common + causes would be updates made in the Google Analytics UI, changes + from customer support, or automatic Google Analytics system + changes. + + Attributes: + id (str): + ID of this change history event. This ID is + unique across Google Analytics. + change_time (google.protobuf.timestamp_pb2.Timestamp): + Time when change was made. + actor_type (google.analytics.admin_v1alpha.types.ActorType): + The type of actor that made this change. + user_actor_email (str): + Email address of the Google account that made + the change. This will be a valid email address + if the actor field is set to USER, and empty + otherwise. Google accounts that have been + deleted will cause an error. + changes_filtered (bool): + If true, then the list of changes returned + was filtered, and does not represent all changes + that occurred in this event. + changes (MutableSequence[google.analytics.admin_v1alpha.types.ChangeHistoryChange]): + A list of changes made in this change history + event that fit the filters specified in + SearchChangeHistoryEventsRequest. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + change_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + actor_type: 'ActorType' = proto.Field( + proto.ENUM, + number=3, + enum='ActorType', + ) + user_actor_email: str = proto.Field( + proto.STRING, + number=4, + ) + changes_filtered: bool = proto.Field( + proto.BOOL, + number=5, + ) + changes: MutableSequence['ChangeHistoryChange'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ChangeHistoryChange', + ) + + +class ChangeHistoryChange(proto.Message): + r"""A description of a change to a single Google Analytics + resource. + + Attributes: + resource (str): + Resource name of the resource whose changes + are described by this entry. + action (google.analytics.admin_v1alpha.types.ActionType): + The type of action that changed this + resource. + resource_before_change (google.analytics.admin_v1alpha.types.ChangeHistoryChange.ChangeHistoryResource): + Resource contents from before the change was + made. If this resource was created in this + change, this field will be missing. + resource_after_change (google.analytics.admin_v1alpha.types.ChangeHistoryChange.ChangeHistoryResource): + Resource contents from after the change was + made. If this resource was deleted in this + change, this field will be missing. + """ + + class ChangeHistoryResource(proto.Message): + r"""A snapshot of a resource as before or after the result of a + change in change history. + + 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: + account (google.analytics.admin_v1alpha.types.Account): + A snapshot of an Account resource in change + history. + + This field is a member of `oneof`_ ``resource``. + property (google.analytics.admin_v1alpha.types.Property): + A snapshot of a Property resource in change + history. + + This field is a member of `oneof`_ ``resource``. + firebase_link (google.analytics.admin_v1alpha.types.FirebaseLink): + A snapshot of a FirebaseLink resource in + change history. + + This field is a member of `oneof`_ ``resource``. + google_ads_link (google.analytics.admin_v1alpha.types.GoogleAdsLink): + A snapshot of a GoogleAdsLink resource in + change history. + + This field is a member of `oneof`_ ``resource``. + google_signals_settings (google.analytics.admin_v1alpha.types.GoogleSignalsSettings): + A snapshot of a GoogleSignalsSettings + resource in change history. + + This field is a member of `oneof`_ ``resource``. + display_video_360_advertiser_link (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLink): + A snapshot of a DisplayVideo360AdvertiserLink + resource in change history. + + This field is a member of `oneof`_ ``resource``. + display_video_360_advertiser_link_proposal (google.analytics.admin_v1alpha.types.DisplayVideo360AdvertiserLinkProposal): + A snapshot of a + DisplayVideo360AdvertiserLinkProposal resource + in change history. + + This field is a member of `oneof`_ ``resource``. + conversion_event (google.analytics.admin_v1alpha.types.ConversionEvent): + A snapshot of a ConversionEvent resource in + change history. + + This field is a member of `oneof`_ ``resource``. + measurement_protocol_secret (google.analytics.admin_v1alpha.types.MeasurementProtocolSecret): + A snapshot of a MeasurementProtocolSecret + resource in change history. + + This field is a member of `oneof`_ ``resource``. + custom_dimension (google.analytics.admin_v1alpha.types.CustomDimension): + A snapshot of a CustomDimension resource in + change history. + + This field is a member of `oneof`_ ``resource``. + custom_metric (google.analytics.admin_v1alpha.types.CustomMetric): + A snapshot of a CustomMetric resource in + change history. + + This field is a member of `oneof`_ ``resource``. + data_retention_settings (google.analytics.admin_v1alpha.types.DataRetentionSettings): + A snapshot of a data retention settings + resource in change history. + + This field is a member of `oneof`_ ``resource``. + search_ads_360_link (google.analytics.admin_v1alpha.types.SearchAds360Link): + A snapshot of a SearchAds360Link resource in + change history. + + This field is a member of `oneof`_ ``resource``. + data_stream (google.analytics.admin_v1alpha.types.DataStream): + A snapshot of a DataStream resource in change + history. + + This field is a member of `oneof`_ ``resource``. + attribution_settings (google.analytics.admin_v1alpha.types.AttributionSettings): + A snapshot of AttributionSettings resource in + change history. + + This field is a member of `oneof`_ ``resource``. + expanded_data_set (google.analytics.admin_v1alpha.types.ExpandedDataSet): + A snapshot of an ExpandedDataSet resource in + change history. + + This field is a member of `oneof`_ ``resource``. + channel_group (google.analytics.admin_v1alpha.types.ChannelGroup): + A snapshot of a ChannelGroup resource in + change history. + + This field is a member of `oneof`_ ``resource``. + bigquery_link (google.analytics.admin_v1alpha.types.BigQueryLink): + A snapshot of a BigQuery link resource in + change history. + + This field is a member of `oneof`_ ``resource``. + enhanced_measurement_settings (google.analytics.admin_v1alpha.types.EnhancedMeasurementSettings): + A snapshot of EnhancedMeasurementSettings + resource in change history. + + This field is a member of `oneof`_ ``resource``. + data_redaction_settings (google.analytics.admin_v1alpha.types.DataRedactionSettings): + A snapshot of DataRedactionSettings resource + in change history. + + This field is a member of `oneof`_ ``resource``. + skadnetwork_conversion_value_schema (google.analytics.admin_v1alpha.types.SKAdNetworkConversionValueSchema): + A snapshot of + SKAdNetworkConversionValueSchema resource in + change history. + + This field is a member of `oneof`_ ``resource``. + adsense_link (google.analytics.admin_v1alpha.types.AdSenseLink): + A snapshot of an AdSenseLink resource in + change history. + + This field is a member of `oneof`_ ``resource``. + audience (google.analytics.admin_v1alpha.types.Audience): + A snapshot of an Audience resource in change + history. + + This field is a member of `oneof`_ ``resource``. + event_create_rule (google.analytics.admin_v1alpha.types.EventCreateRule): + A snapshot of an EventCreateRule resource in + change history. + + This field is a member of `oneof`_ ``resource``. + calculated_metric (google.analytics.admin_v1alpha.types.CalculatedMetric): + A snapshot of a CalculatedMetric resource in + change history. + + This field is a member of `oneof`_ ``resource``. + """ + + account: 'Account' = proto.Field( + proto.MESSAGE, + number=1, + oneof='resource', + message='Account', + ) + property: 'Property' = proto.Field( + proto.MESSAGE, + number=2, + oneof='resource', + message='Property', + ) + firebase_link: 'FirebaseLink' = proto.Field( + proto.MESSAGE, + number=6, + oneof='resource', + message='FirebaseLink', + ) + google_ads_link: 'GoogleAdsLink' = proto.Field( + proto.MESSAGE, + number=7, + oneof='resource', + message='GoogleAdsLink', + ) + google_signals_settings: 'GoogleSignalsSettings' = proto.Field( + proto.MESSAGE, + number=8, + oneof='resource', + message='GoogleSignalsSettings', + ) + display_video_360_advertiser_link: 'DisplayVideo360AdvertiserLink' = proto.Field( + proto.MESSAGE, + number=9, + oneof='resource', + message='DisplayVideo360AdvertiserLink', + ) + display_video_360_advertiser_link_proposal: 'DisplayVideo360AdvertiserLinkProposal' = proto.Field( + proto.MESSAGE, + number=10, + oneof='resource', + message='DisplayVideo360AdvertiserLinkProposal', + ) + conversion_event: 'ConversionEvent' = proto.Field( + proto.MESSAGE, + number=11, + oneof='resource', + message='ConversionEvent', + ) + measurement_protocol_secret: 'MeasurementProtocolSecret' = proto.Field( + proto.MESSAGE, + number=12, + oneof='resource', + message='MeasurementProtocolSecret', + ) + custom_dimension: 'CustomDimension' = proto.Field( + proto.MESSAGE, + number=13, + oneof='resource', + message='CustomDimension', + ) + custom_metric: 'CustomMetric' = proto.Field( + proto.MESSAGE, + number=14, + oneof='resource', + message='CustomMetric', + ) + data_retention_settings: 'DataRetentionSettings' = proto.Field( + proto.MESSAGE, + number=15, + oneof='resource', + message='DataRetentionSettings', + ) + search_ads_360_link: 'SearchAds360Link' = proto.Field( + proto.MESSAGE, + number=16, + oneof='resource', + message='SearchAds360Link', + ) + data_stream: 'DataStream' = proto.Field( + proto.MESSAGE, + number=18, + oneof='resource', + message='DataStream', + ) + attribution_settings: 'AttributionSettings' = proto.Field( + proto.MESSAGE, + number=20, + oneof='resource', + message='AttributionSettings', + ) + expanded_data_set: gaa_expanded_data_set.ExpandedDataSet = proto.Field( + proto.MESSAGE, + number=21, + oneof='resource', + message=gaa_expanded_data_set.ExpandedDataSet, + ) + channel_group: gaa_channel_group.ChannelGroup = proto.Field( + proto.MESSAGE, + number=22, + oneof='resource', + message=gaa_channel_group.ChannelGroup, + ) + bigquery_link: 'BigQueryLink' = proto.Field( + proto.MESSAGE, + number=23, + oneof='resource', + message='BigQueryLink', + ) + enhanced_measurement_settings: 'EnhancedMeasurementSettings' = proto.Field( + proto.MESSAGE, + number=24, + oneof='resource', + message='EnhancedMeasurementSettings', + ) + data_redaction_settings: 'DataRedactionSettings' = proto.Field( + proto.MESSAGE, + number=25, + oneof='resource', + message='DataRedactionSettings', + ) + skadnetwork_conversion_value_schema: 'SKAdNetworkConversionValueSchema' = proto.Field( + proto.MESSAGE, + number=26, + oneof='resource', + message='SKAdNetworkConversionValueSchema', + ) + adsense_link: 'AdSenseLink' = proto.Field( + proto.MESSAGE, + number=27, + oneof='resource', + message='AdSenseLink', + ) + audience: gaa_audience.Audience = proto.Field( + proto.MESSAGE, + number=28, + oneof='resource', + message=gaa_audience.Audience, + ) + event_create_rule: event_create_and_edit.EventCreateRule = proto.Field( + proto.MESSAGE, + number=29, + oneof='resource', + message=event_create_and_edit.EventCreateRule, + ) + calculated_metric: 'CalculatedMetric' = proto.Field( + proto.MESSAGE, + number=31, + oneof='resource', + message='CalculatedMetric', + ) + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + action: 'ActionType' = proto.Field( + proto.ENUM, + number=2, + enum='ActionType', + ) + resource_before_change: ChangeHistoryResource = proto.Field( + proto.MESSAGE, + number=3, + message=ChangeHistoryResource, + ) + resource_after_change: ChangeHistoryResource = proto.Field( + proto.MESSAGE, + number=4, + message=ChangeHistoryResource, + ) + + +class DisplayVideo360AdvertiserLink(proto.Message): + r"""A link between a GA4 property and a Display & Video 360 + advertiser. + + Attributes: + name (str): + Output only. The resource name for this + DisplayVideo360AdvertiserLink resource. Format: + + properties/{propertyId}/displayVideo360AdvertiserLinks/{linkId} + + Note: linkId is not the Display & Video 360 + Advertiser ID + advertiser_id (str): + Immutable. The Display & Video 360 + Advertiser's advertiser ID. + advertiser_display_name (str): + Output only. The display name of the Display + & Video 360 Advertiser. + ads_personalization_enabled (google.protobuf.wrappers_pb2.BoolValue): + Enables personalized advertising features + with this integration. If this field is not set + on create/update, it will be defaulted to true. + campaign_data_sharing_enabled (google.protobuf.wrappers_pb2.BoolValue): + Immutable. Enables the import of campaign + data from Display & Video 360 into the GA4 + property. After link creation, this can only be + updated from the Display & Video 360 product. If + this field is not set on create, it will be + defaulted to true. + cost_data_sharing_enabled (google.protobuf.wrappers_pb2.BoolValue): + Immutable. Enables the import of cost data from Display & + Video 360 into the GA4 property. This can only be enabled if + campaign_data_sharing_enabled is enabled. After link + creation, this can only be updated from the Display & Video + 360 product. If this field is not set on create, it will be + defaulted to true. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + advertiser_id: str = proto.Field( + proto.STRING, + number=2, + ) + advertiser_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + ads_personalization_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.BoolValue, + ) + campaign_data_sharing_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.BoolValue, + ) + cost_data_sharing_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.BoolValue, + ) + + +class DisplayVideo360AdvertiserLinkProposal(proto.Message): + r"""A proposal for a link between a GA4 property and a Display & + Video 360 advertiser. + + A proposal is converted to a DisplayVideo360AdvertiserLink once + approved. Google Analytics admins approve inbound proposals + while Display & Video 360 admins approve outbound proposals. + + Attributes: + name (str): + Output only. The resource name for this + DisplayVideo360AdvertiserLinkProposal resource. + Format: + + properties/{propertyId}/displayVideo360AdvertiserLinkProposals/{proposalId} + + Note: proposalId is not the Display & Video 360 + Advertiser ID + advertiser_id (str): + Immutable. The Display & Video 360 + Advertiser's advertiser ID. + link_proposal_status_details (google.analytics.admin_v1alpha.types.LinkProposalStatusDetails): + Output only. The status information for this + link proposal. + advertiser_display_name (str): + Output only. The display name of the Display + & Video Advertiser. Only populated for proposals + that originated from Display & Video 360. + validation_email (str): + Input only. On a proposal being sent to + Display & Video 360, this field must be set to + the email address of an admin on the target + advertiser. This is used to verify that the + Google Analytics admin is aware of at least one + admin on the Display & Video 360 Advertiser. + This does not restrict approval of the proposal + to a single user. Any admin on the Display & + Video 360 Advertiser may approve the proposal. + ads_personalization_enabled (google.protobuf.wrappers_pb2.BoolValue): + Immutable. Enables personalized advertising + features with this integration. If this field is + not set on create, it will be defaulted to true. + campaign_data_sharing_enabled (google.protobuf.wrappers_pb2.BoolValue): + Immutable. Enables the import of campaign + data from Display & Video 360. If this field is + not set on create, it will be defaulted to true. + cost_data_sharing_enabled (google.protobuf.wrappers_pb2.BoolValue): + Immutable. Enables the import of cost data from Display & + Video 360. This can only be enabled if + campaign_data_sharing_enabled is enabled. If this field is + not set on create, it will be defaulted to true. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + advertiser_id: str = proto.Field( + proto.STRING, + number=2, + ) + link_proposal_status_details: 'LinkProposalStatusDetails' = proto.Field( + proto.MESSAGE, + number=3, + message='LinkProposalStatusDetails', + ) + advertiser_display_name: str = proto.Field( + proto.STRING, + number=4, + ) + validation_email: str = proto.Field( + proto.STRING, + number=5, + ) + ads_personalization_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.BoolValue, + ) + campaign_data_sharing_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.BoolValue, + ) + cost_data_sharing_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=8, + message=wrappers_pb2.BoolValue, + ) + + +class SearchAds360Link(proto.Message): + r"""A link between a GA4 property and a Search Ads 360 entity. + + Attributes: + name (str): + Output only. The resource name for this + SearchAds360Link resource. Format: + properties/{propertyId}/searchAds360Links/{linkId} + + Note: linkId is not the Search Ads 360 + advertiser ID + advertiser_id (str): + Immutable. This field represents the + Advertiser ID of the Search Ads 360 Advertiser. + that has been linked. + campaign_data_sharing_enabled (google.protobuf.wrappers_pb2.BoolValue): + Immutable. Enables the import of campaign + data from Search Ads 360 into the GA4 property. + After link creation, this can only be updated + from the Search Ads 360 product. + If this field is not set on create, it will be + defaulted to true. + cost_data_sharing_enabled (google.protobuf.wrappers_pb2.BoolValue): + Immutable. Enables the import of cost data from Search Ads + 360 to the GA4 property. This can only be enabled if + campaign_data_sharing_enabled is enabled. After link + creation, this can only be updated from the Search Ads 360 + product. If this field is not set on create, it will be + defaulted to true. + advertiser_display_name (str): + Output only. The display name of the Search + Ads 360 Advertiser. Allows users to easily + identify the linked resource. + ads_personalization_enabled (google.protobuf.wrappers_pb2.BoolValue): + Enables personalized advertising features + with this integration. If this field is not set + on create, it will be defaulted to true. + site_stats_sharing_enabled (google.protobuf.wrappers_pb2.BoolValue): + Enables export of site stats with this + integration. If this field is not set on create, + it will be defaulted to true. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + advertiser_id: str = proto.Field( + proto.STRING, + number=2, + ) + campaign_data_sharing_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.BoolValue, + ) + cost_data_sharing_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.BoolValue, + ) + advertiser_display_name: str = proto.Field( + proto.STRING, + number=5, + ) + ads_personalization_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.BoolValue, + ) + site_stats_sharing_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.BoolValue, + ) + + +class LinkProposalStatusDetails(proto.Message): + r"""Status information for a link proposal. + + Attributes: + link_proposal_initiating_product (google.analytics.admin_v1alpha.types.LinkProposalInitiatingProduct): + Output only. The source of this proposal. + requestor_email (str): + Output only. The email address of the user + that proposed this linkage. + link_proposal_state (google.analytics.admin_v1alpha.types.LinkProposalState): + Output only. The state of this proposal. + """ + + link_proposal_initiating_product: 'LinkProposalInitiatingProduct' = proto.Field( + proto.ENUM, + number=1, + enum='LinkProposalInitiatingProduct', + ) + requestor_email: str = proto.Field( + proto.STRING, + number=2, + ) + link_proposal_state: 'LinkProposalState' = proto.Field( + proto.ENUM, + number=3, + enum='LinkProposalState', + ) + + +class ConversionEvent(proto.Message): + r"""A conversion event in a Google Analytics property. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Resource name of this conversion event. Format: + properties/{property}/conversionEvents/{conversion_event} + event_name (str): + Immutable. The event name for this conversion + event. Examples: 'click', 'purchase' + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this conversion event + was created in the property. + deletable (bool): + Output only. If set, this event can currently + be deleted with DeleteConversionEvent. + custom (bool): + Output only. If set to true, this conversion + event refers to a custom event. If set to + false, this conversion event refers to a default + event in GA. Default events typically have + special meaning in GA. Default events are + usually created for you by the GA system, but in + some cases can be created by property admins. + Custom events count towards the maximum number + of custom conversion events that may be created + per property. + counting_method (google.analytics.admin_v1alpha.types.ConversionEvent.ConversionCountingMethod): + Optional. The method by which conversions will be counted + across multiple events within a session. If this value is + not provided, it will be set to ``ONCE_PER_EVENT``. + default_conversion_value (google.analytics.admin_v1alpha.types.ConversionEvent.DefaultConversionValue): + Optional. Defines a default value/currency + for a conversion event. + + This field is a member of `oneof`_ ``_default_conversion_value``. + """ + class ConversionCountingMethod(proto.Enum): + r"""The method by which conversions will be counted across + multiple events within a session. + + Values: + CONVERSION_COUNTING_METHOD_UNSPECIFIED (0): + Counting method not specified. + ONCE_PER_EVENT (1): + Each Event instance is considered a + Conversion. + ONCE_PER_SESSION (2): + An Event instance is considered a Conversion + at most once per session per user. + """ + CONVERSION_COUNTING_METHOD_UNSPECIFIED = 0 + ONCE_PER_EVENT = 1 + ONCE_PER_SESSION = 2 + + class DefaultConversionValue(proto.Message): + r"""Defines a default value/currency for a conversion event. Both + value and currency must be provided. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (float): + This value will be used to populate the value for all + conversions of the specified event_name where the event + "value" parameter is unset. + + This field is a member of `oneof`_ ``_value``. + currency_code (str): + When a conversion event for this event_name has no set + currency, this currency will be applied as the default. Must + be in ISO 4217 currency code format. See + https://en.wikipedia.org/wiki/ISO_4217 for more information. + + This field is a member of `oneof`_ ``_currency_code``. + """ + + value: float = proto.Field( + proto.DOUBLE, + number=1, + optional=True, + ) + currency_code: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + event_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + deletable: bool = proto.Field( + proto.BOOL, + number=4, + ) + custom: bool = proto.Field( + proto.BOOL, + number=5, + ) + counting_method: ConversionCountingMethod = proto.Field( + proto.ENUM, + number=6, + enum=ConversionCountingMethod, + ) + default_conversion_value: DefaultConversionValue = proto.Field( + proto.MESSAGE, + number=7, + optional=True, + message=DefaultConversionValue, + ) + + +class KeyEvent(proto.Message): + r"""A key event in a Google Analytics property. + + Attributes: + name (str): + Output only. Resource name of this key event. Format: + properties/{property}/keyEvents/{key_event} + event_name (str): + Immutable. The event name for this key event. + Examples: 'click', 'purchase' + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this key event was + created in the property. + deletable (bool): + Output only. If set to true, this event can + be deleted. + custom (bool): + Output only. If set to true, this key event + refers to a custom event. If set to false, this + key event refers to a default event in GA. + Default events typically have special meaning in + GA. Default events are usually created for you + by the GA system, but in some cases can be + created by property admins. Custom events count + towards the maximum number of custom key events + that may be created per property. + counting_method (google.analytics.admin_v1alpha.types.KeyEvent.CountingMethod): + Required. The method by which Key Events will + be counted across multiple events within a + session. + default_value (google.analytics.admin_v1alpha.types.KeyEvent.DefaultValue): + Optional. Defines a default value/currency + for a key event. + """ + class CountingMethod(proto.Enum): + r"""The method by which Key Events will be counted across + multiple events within a session. + + Values: + COUNTING_METHOD_UNSPECIFIED (0): + Counting method not specified. + ONCE_PER_EVENT (1): + Each Event instance is considered a Key + Event. + ONCE_PER_SESSION (2): + An Event instance is considered a Key Event + at most once per session per user. + """ + COUNTING_METHOD_UNSPECIFIED = 0 + ONCE_PER_EVENT = 1 + ONCE_PER_SESSION = 2 + + class DefaultValue(proto.Message): + r"""Defines a default value/currency for a key event. + + Attributes: + numeric_value (float): + Required. This will be used to populate the "value" + parameter for all occurrences of this Key Event (specified + by event_name) where that parameter is unset. + currency_code (str): + Required. When an occurrence of this Key Event (specified by + event_name) has no set currency this currency will be + applied as the default. Must be in ISO 4217 currency code + format. + + See https://en.wikipedia.org/wiki/ISO_4217 for more + information. + """ + + numeric_value: float = proto.Field( + proto.DOUBLE, + number=1, + ) + currency_code: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + event_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + deletable: bool = proto.Field( + proto.BOOL, + number=4, + ) + custom: bool = proto.Field( + proto.BOOL, + number=5, + ) + counting_method: CountingMethod = proto.Field( + proto.ENUM, + number=6, + enum=CountingMethod, + ) + default_value: DefaultValue = proto.Field( + proto.MESSAGE, + number=7, + message=DefaultValue, + ) + + +class GoogleSignalsSettings(proto.Message): + r"""Settings values for Google Signals. This is a singleton + resource. + + Attributes: + name (str): + Output only. Resource name of this setting. Format: + properties/{property_id}/googleSignalsSettings Example: + "properties/1000/googleSignalsSettings". + state (google.analytics.admin_v1alpha.types.GoogleSignalsState): + Status of this setting. + consent (google.analytics.admin_v1alpha.types.GoogleSignalsConsent): + Output only. Terms of Service acceptance. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: 'GoogleSignalsState' = proto.Field( + proto.ENUM, + number=3, + enum='GoogleSignalsState', + ) + consent: 'GoogleSignalsConsent' = proto.Field( + proto.ENUM, + number=4, + enum='GoogleSignalsConsent', + ) + + +class CustomDimension(proto.Message): + r"""A definition for a CustomDimension. + + Attributes: + name (str): + Output only. Resource name for this + CustomDimension resource. Format: + properties/{property}/customDimensions/{customDimension} + parameter_name (str): + Required. Immutable. Tagging parameter name + for this custom dimension. + If this is a user-scoped dimension, then this is + the user property name. If this is an + event-scoped dimension, then this is the event + parameter name. + + If this is an item-scoped dimension, then this + is the parameter name found in the eCommerce + items array. + + May only contain alphanumeric and underscore + characters, starting with a letter. Max length + of 24 characters for user-scoped dimensions, 40 + characters for event-scoped dimensions. + display_name (str): + Required. Display name for this custom + dimension as shown in the Analytics UI. Max + length of 82 characters, alphanumeric plus space + and underscore starting with a letter. Legacy + system-generated display names may contain + square brackets, but updates to this field will + never permit square brackets. + description (str): + Optional. Description for this custom + dimension. Max length of 150 characters. + scope (google.analytics.admin_v1alpha.types.CustomDimension.DimensionScope): + Required. Immutable. The scope of this + dimension. + disallow_ads_personalization (bool): + Optional. If set to true, sets this dimension + as NPA and excludes it from ads personalization. + + This is currently only supported by user-scoped + custom dimensions. + """ + class DimensionScope(proto.Enum): + r"""Valid values for the scope of this dimension. + + Values: + DIMENSION_SCOPE_UNSPECIFIED (0): + Scope unknown or not specified. + EVENT (1): + Dimension scoped to an event. + USER (2): + Dimension scoped to a user. + ITEM (3): + Dimension scoped to eCommerce items + """ + DIMENSION_SCOPE_UNSPECIFIED = 0 + EVENT = 1 + USER = 2 + ITEM = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parameter_name: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + scope: DimensionScope = proto.Field( + proto.ENUM, + number=5, + enum=DimensionScope, + ) + disallow_ads_personalization: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class CustomMetric(proto.Message): + r"""A definition for a custom metric. + + Attributes: + name (str): + Output only. Resource name for this + CustomMetric resource. Format: + properties/{property}/customMetrics/{customMetric} + parameter_name (str): + Required. Immutable. Tagging name for this + custom metric. + If this is an event-scoped metric, then this is + the event parameter name. + + May only contain alphanumeric and underscore + charactes, starting with a letter. Max length of + 40 characters for event-scoped metrics. + display_name (str): + Required. Display name for this custom metric + as shown in the Analytics UI. Max length of 82 + characters, alphanumeric plus space and + underscore starting with a letter. Legacy + system-generated display names may contain + square brackets, but updates to this field will + never permit square brackets. + description (str): + Optional. Description for this custom + dimension. Max length of 150 characters. + measurement_unit (google.analytics.admin_v1alpha.types.CustomMetric.MeasurementUnit): + Required. The type for the custom metric's + value. + scope (google.analytics.admin_v1alpha.types.CustomMetric.MetricScope): + Required. Immutable. The scope of this custom + metric. + restricted_metric_type (MutableSequence[google.analytics.admin_v1alpha.types.CustomMetric.RestrictedMetricType]): + Optional. Types of restricted data that this + metric may contain. Required for metrics with + CURRENCY measurement unit. Must be empty for + metrics with a non-CURRENCY measurement unit. + """ + class MeasurementUnit(proto.Enum): + r"""Possible types of representing the custom metric's value. + + Currency representation may change in the future, requiring a + breaking API change. + + Values: + MEASUREMENT_UNIT_UNSPECIFIED (0): + MeasurementUnit unspecified or missing. + STANDARD (1): + This metric uses default units. + CURRENCY (2): + This metric measures a currency. + FEET (3): + This metric measures feet. + METERS (4): + This metric measures meters. + KILOMETERS (5): + This metric measures kilometers. + MILES (6): + This metric measures miles. + MILLISECONDS (7): + This metric measures milliseconds. + SECONDS (8): + This metric measures seconds. + MINUTES (9): + This metric measures minutes. + HOURS (10): + This metric measures hours. + """ + MEASUREMENT_UNIT_UNSPECIFIED = 0 + STANDARD = 1 + CURRENCY = 2 + FEET = 3 + METERS = 4 + KILOMETERS = 5 + MILES = 6 + MILLISECONDS = 7 + SECONDS = 8 + MINUTES = 9 + HOURS = 10 + + class MetricScope(proto.Enum): + r"""The scope of this metric. + + Values: + METRIC_SCOPE_UNSPECIFIED (0): + Scope unknown or not specified. + EVENT (1): + Metric scoped to an event. + """ + METRIC_SCOPE_UNSPECIFIED = 0 + EVENT = 1 + + class RestrictedMetricType(proto.Enum): + r"""Labels that mark the data in this custom metric as data that + should be restricted to specific users. + + Values: + RESTRICTED_METRIC_TYPE_UNSPECIFIED (0): + Type unknown or unspecified. + COST_DATA (1): + Metric reports cost data. + REVENUE_DATA (2): + Metric reports revenue data. + """ + RESTRICTED_METRIC_TYPE_UNSPECIFIED = 0 + COST_DATA = 1 + REVENUE_DATA = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parameter_name: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + measurement_unit: MeasurementUnit = proto.Field( + proto.ENUM, + number=5, + enum=MeasurementUnit, + ) + scope: MetricScope = proto.Field( + proto.ENUM, + number=6, + enum=MetricScope, + ) + restricted_metric_type: MutableSequence[RestrictedMetricType] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=RestrictedMetricType, + ) + + +class CalculatedMetric(proto.Message): + r"""A definition for a calculated metric. + + Attributes: + name (str): + Output only. Resource name for this CalculatedMetric. + Format: + 'properties/{property_id}/calculatedMetrics/{calculated_metric_id}' + description (str): + Optional. Description for this calculated + metric. Max length of 4096 characters. + display_name (str): + Required. Display name for this calculated + metric as shown in the Google Analytics UI. Max + length 82 characters. + calculated_metric_id (str): + Output only. The ID to use for the calculated metric. In the + UI, this is referred to as the "API name." + + The calculated_metric_id is used when referencing this + calculated metric from external APIs. For example, + "calcMetric:{calculated_metric_id}". + metric_unit (google.analytics.admin_v1alpha.types.CalculatedMetric.MetricUnit): + Required. The type for the calculated + metric's value. + restricted_metric_type (MutableSequence[google.analytics.admin_v1alpha.types.CalculatedMetric.RestrictedMetricType]): + Output only. Types of restricted data that + this metric contains. + formula (str): + Required. The calculated metric's definition. Maximum number + of unique referenced custom metrics is 5. Formulas supports + the following operations: + + - (addition), - (subtraction), - (negative), \* + (multiplication), / (division), () (parenthesis). Any + valid real numbers are acceptable that fit in a Long + (64bit integer) or a Double (64 bit floating point + number). Example formula: "( customEvent:parameter_name + + cartPurchaseQuantity ) / 2.0". + invalid_metric_reference (bool): + Output only. If true, this calculated metric has a invalid + metric reference. Anything using a calculated metric with + invalid_metric_reference set to true may fail, produce + warnings, or produce unexpected results. + """ + class MetricUnit(proto.Enum): + r"""Possible types of representing the calculated metric's value. + + Values: + METRIC_UNIT_UNSPECIFIED (0): + MetricUnit unspecified or missing. + STANDARD (1): + This metric uses default units. + CURRENCY (2): + This metric measures a currency. + FEET (3): + This metric measures feet. + MILES (4): + This metric measures miles. + METERS (5): + This metric measures meters. + KILOMETERS (6): + This metric measures kilometers. + MILLISECONDS (7): + This metric measures milliseconds. + SECONDS (8): + This metric measures seconds. + MINUTES (9): + This metric measures minutes. + HOURS (10): + This metric measures hours. + """ + METRIC_UNIT_UNSPECIFIED = 0 + STANDARD = 1 + CURRENCY = 2 + FEET = 3 + MILES = 4 + METERS = 5 + KILOMETERS = 6 + MILLISECONDS = 7 + SECONDS = 8 + MINUTES = 9 + HOURS = 10 + + class RestrictedMetricType(proto.Enum): + r"""Labels that mark the data in calculated metric used in + conjunction with user roles that restrict access to cost and/or + revenue metrics. + + Values: + RESTRICTED_METRIC_TYPE_UNSPECIFIED (0): + Type unknown or unspecified. + COST_DATA (1): + Metric reports cost data. + REVENUE_DATA (2): + Metric reports revenue data. + """ + RESTRICTED_METRIC_TYPE_UNSPECIFIED = 0 + COST_DATA = 1 + REVENUE_DATA = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + calculated_metric_id: str = proto.Field( + proto.STRING, + number=4, + ) + metric_unit: MetricUnit = proto.Field( + proto.ENUM, + number=5, + enum=MetricUnit, + ) + restricted_metric_type: MutableSequence[RestrictedMetricType] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=RestrictedMetricType, + ) + formula: str = proto.Field( + proto.STRING, + number=7, + ) + invalid_metric_reference: bool = proto.Field( + proto.BOOL, + number=9, + ) + + +class DataRetentionSettings(proto.Message): + r"""Settings values for data retention. This is a singleton + resource. + + Attributes: + name (str): + Output only. Resource name for this + DataRetentionSetting resource. Format: + properties/{property}/dataRetentionSettings + event_data_retention (google.analytics.admin_v1alpha.types.DataRetentionSettings.RetentionDuration): + The length of time that event-level data is + retained. + reset_user_data_on_new_activity (bool): + If true, reset the retention period for the + user identifier with every event from that user. + """ + class RetentionDuration(proto.Enum): + r"""Valid values for the data retention duration. + + Values: + RETENTION_DURATION_UNSPECIFIED (0): + Data retention time duration is not + specified. + TWO_MONTHS (1): + The data retention time duration is 2 months. + FOURTEEN_MONTHS (3): + The data retention time duration is 14 + months. + TWENTY_SIX_MONTHS (4): + The data retention time duration is 26 + months. Available to 360 properties only. + THIRTY_EIGHT_MONTHS (5): + The data retention time duration is 38 + months. Available to 360 properties only. + FIFTY_MONTHS (6): + The data retention time duration is 50 + months. Available to 360 properties only. + """ + RETENTION_DURATION_UNSPECIFIED = 0 + TWO_MONTHS = 1 + FOURTEEN_MONTHS = 3 + TWENTY_SIX_MONTHS = 4 + THIRTY_EIGHT_MONTHS = 5 + FIFTY_MONTHS = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + event_data_retention: RetentionDuration = proto.Field( + proto.ENUM, + number=2, + enum=RetentionDuration, + ) + reset_user_data_on_new_activity: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class AttributionSettings(proto.Message): + r"""The attribution settings used for a given property. This is a + singleton resource. + + Attributes: + name (str): + Output only. Resource name of this attribution settings + resource. Format: + properties/{property_id}/attributionSettings Example: + "properties/1000/attributionSettings". + acquisition_conversion_event_lookback_window (google.analytics.admin_v1alpha.types.AttributionSettings.AcquisitionConversionEventLookbackWindow): + Required. The lookback window configuration + for acquisition conversion events. The default + window size is 30 days. + other_conversion_event_lookback_window (google.analytics.admin_v1alpha.types.AttributionSettings.OtherConversionEventLookbackWindow): + Required. The lookback window for all other, + non-acquisition conversion events. The default + window size is 90 days. + reporting_attribution_model (google.analytics.admin_v1alpha.types.AttributionSettings.ReportingAttributionModel): + Required. The reporting attribution model + used to calculate conversion credit in this + property's reports. + + Changing the attribution model will apply to + both historical and future data. These changes + will be reflected in reports with conversion and + revenue data. User and session data will be + unaffected. + ads_web_conversion_data_export_scope (google.analytics.admin_v1alpha.types.AttributionSettings.AdsWebConversionDataExportScope): + Required. The Conversion Export Scope for + data exported to linked Ads Accounts. + """ + class AcquisitionConversionEventLookbackWindow(proto.Enum): + r"""How far back in time events should be considered for + inclusion in a converting path which leads to the first install + of an app or the first visit to a site. + + Values: + ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_UNSPECIFIED (0): + Lookback window size unspecified. + ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS (1): + 7-day lookback window. + ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS (2): + 30-day lookback window. + """ + ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_UNSPECIFIED = 0 + ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS = 1 + ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS = 2 + + class OtherConversionEventLookbackWindow(proto.Enum): + r"""How far back in time events should be considered for + inclusion in a converting path for all conversions other than + first app install/first site visit. + + Values: + OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_UNSPECIFIED (0): + Lookback window size unspecified. + OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS (1): + 30-day lookback window. + OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_60_DAYS (2): + 60-day lookback window. + OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_90_DAYS (3): + 90-day lookback window. + """ + OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_UNSPECIFIED = 0 + OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS = 1 + OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_60_DAYS = 2 + OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_90_DAYS = 3 + + class ReportingAttributionModel(proto.Enum): + r"""The reporting attribution model used to calculate conversion + credit in this property's reports. + + Values: + REPORTING_ATTRIBUTION_MODEL_UNSPECIFIED (0): + Reporting attribution model unspecified. + PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN (1): + Data-driven attribution distributes credit for the + conversion based on data for each conversion event. Each + Data-driven model is specific to each advertiser and each + conversion event. Previously CROSS_CHANNEL_DATA_DRIVEN + PAID_AND_ORGANIC_CHANNELS_LAST_CLICK (2): + Ignores direct traffic and attributes 100% of the conversion + value to the last channel that the customer clicked through + (or engaged view through for YouTube) before converting. + Previously CROSS_CHANNEL_LAST_CLICK + GOOGLE_PAID_CHANNELS_LAST_CLICK (7): + Attributes 100% of the conversion value to the last Google + Paid channel that the customer clicked through before + converting. Previously ADS_PREFERRED_LAST_CLICK + """ + REPORTING_ATTRIBUTION_MODEL_UNSPECIFIED = 0 + PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN = 1 + PAID_AND_ORGANIC_CHANNELS_LAST_CLICK = 2 + GOOGLE_PAID_CHANNELS_LAST_CLICK = 7 + + class AdsWebConversionDataExportScope(proto.Enum): + r"""The Conversion Export Scope for data exported to linked Ads + Accounts. + + Values: + ADS_WEB_CONVERSION_DATA_EXPORT_SCOPE_UNSPECIFIED (0): + Default value. This value is unused. + NOT_SELECTED_YET (1): + No data export scope selected yet. + Export scope can never be changed back to this + value. + PAID_AND_ORGANIC_CHANNELS (2): + Paid and organic channels are eligible to receive conversion + credit, but only credit assigned to Google Ads channels will + appear in your Ads accounts. To learn more, see `Paid and + Organic + channels `__. + GOOGLE_PAID_CHANNELS (3): + Only Google Ads paid channels are eligible to receive + conversion credit. To learn more, see `Google Paid + channels `__. + """ + ADS_WEB_CONVERSION_DATA_EXPORT_SCOPE_UNSPECIFIED = 0 + NOT_SELECTED_YET = 1 + PAID_AND_ORGANIC_CHANNELS = 2 + GOOGLE_PAID_CHANNELS = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + acquisition_conversion_event_lookback_window: AcquisitionConversionEventLookbackWindow = proto.Field( + proto.ENUM, + number=2, + enum=AcquisitionConversionEventLookbackWindow, + ) + other_conversion_event_lookback_window: OtherConversionEventLookbackWindow = proto.Field( + proto.ENUM, + number=3, + enum=OtherConversionEventLookbackWindow, + ) + reporting_attribution_model: ReportingAttributionModel = proto.Field( + proto.ENUM, + number=4, + enum=ReportingAttributionModel, + ) + ads_web_conversion_data_export_scope: AdsWebConversionDataExportScope = proto.Field( + proto.ENUM, + number=5, + enum=AdsWebConversionDataExportScope, + ) + + +class AccessBinding(proto.Message): + r"""A binding of a user to a set of roles. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user (str): + If set, the email address of the user to set + roles for. Format: "someuser@gmail.com". + + This field is a member of `oneof`_ ``access_target``. + name (str): + Output only. Resource name of this binding. + + Format: accounts/{account}/accessBindings/{access_binding} + or properties/{property}/accessBindings/{access_binding} + + Example: "accounts/100/accessBindings/200". + roles (MutableSequence[str]): + A list of roles for to grant to the parent + resource. + Valid values: + + predefinedRoles/viewer + predefinedRoles/analyst + predefinedRoles/editor + predefinedRoles/admin + predefinedRoles/no-cost-data + predefinedRoles/no-revenue-data + + For users, if an empty list of roles is set, + this AccessBinding will be deleted. + """ + + user: str = proto.Field( + proto.STRING, + number=2, + oneof='access_target', + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + roles: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class BigQueryLink(proto.Message): + r"""A link between a GA4 Property and BigQuery project. + + Attributes: + name (str): + Output only. Resource name of this BigQuery link. Format: + 'properties/{property_id}/bigQueryLinks/{bigquery_link_id}' + Format: 'properties/1234/bigQueryLinks/abc567' + project (str): + Immutable. The linked Google Cloud project. + When creating a BigQueryLink, you may provide + this resource name using either a project number + or project ID. Once this resource has been + created, the returned project will always have a + project that contains a project number. Format: + 'projects/{project number}' + Example: 'projects/1234' + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the link was created. + daily_export_enabled (bool): + If set true, enables daily data export to the + linked Google Cloud project. + streaming_export_enabled (bool): + If set true, enables streaming export to the + linked Google Cloud project. + fresh_daily_export_enabled (bool): + If set true, enables fresh daily export to + the linked Google Cloud project. + include_advertising_id (bool): + If set true, exported data will include + advertising identifiers for mobile app streams. + export_streams (MutableSequence[str]): + The list of streams under the parent property for which data + will be exported. Format: + properties/{property_id}/dataStreams/{stream_id} Example: + ['properties/1000/dataStreams/2000'] + excluded_events (MutableSequence[str]): + The list of event names that will be excluded + from exports. + dataset_location (str): + Required. Immutable. The geographic location + where the created BigQuery dataset should + reside. See + https://cloud.google.com/bigquery/docs/locations + for supported locations. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + daily_export_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + streaming_export_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + fresh_daily_export_enabled: bool = proto.Field( + proto.BOOL, + number=9, + ) + include_advertising_id: bool = proto.Field( + proto.BOOL, + number=6, + ) + export_streams: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + excluded_events: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + dataset_location: str = proto.Field( + proto.STRING, + number=10, + ) + + +class EnhancedMeasurementSettings(proto.Message): + r"""Singleton resource under a web DataStream, configuring + measurement of additional site interactions and content. + + Attributes: + name (str): + Output only. Resource name of the Enhanced Measurement + Settings. Format: + properties/{property_id}/dataStreams/{data_stream}/enhancedMeasurementSettings + Example: + "properties/1000/dataStreams/2000/enhancedMeasurementSettings". + stream_enabled (bool): + Indicates whether Enhanced Measurement + Settings will be used to automatically measure + interactions and content on this web stream. + + Changing this value does not affect the settings + themselves, but determines whether they are + respected. + scrolls_enabled (bool): + If enabled, capture scroll events each time a + visitor gets to the bottom of a page. + outbound_clicks_enabled (bool): + If enabled, capture an outbound click event + each time a visitor clicks a link that leads + them away from your domain. + site_search_enabled (bool): + If enabled, capture a view search results + event each time a visitor performs a search on + your site (based on a query parameter). + video_engagement_enabled (bool): + If enabled, capture video play, progress, and + complete events as visitors view embedded videos + on your site. + file_downloads_enabled (bool): + If enabled, capture a file download event + each time a link is clicked with a common + document, compressed file, application, video, + or audio extension. + page_changes_enabled (bool): + If enabled, capture a page view event each + time the website changes the browser history + state. + form_interactions_enabled (bool): + If enabled, capture a form interaction event + each time a visitor interacts with a form on + your website. False by default. + search_query_parameter (str): + Required. URL query parameters to interpret + as site search parameters. Max length is 1024 + characters. Must not be empty. + uri_query_parameter (str): + Additional URL query parameters. + Max length is 1024 characters. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + stream_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + scrolls_enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + outbound_clicks_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + site_search_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + video_engagement_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + file_downloads_enabled: bool = proto.Field( + proto.BOOL, + number=7, + ) + page_changes_enabled: bool = proto.Field( + proto.BOOL, + number=8, + ) + form_interactions_enabled: bool = proto.Field( + proto.BOOL, + number=9, + ) + search_query_parameter: str = proto.Field( + proto.STRING, + number=10, + ) + uri_query_parameter: str = proto.Field( + proto.STRING, + number=11, + ) + + +class ConnectedSiteTag(proto.Message): + r"""Configuration for a specific Connected Site Tag. + + Attributes: + display_name (str): + Required. User-provided display name for the + connected site tag. Must be less than 256 + characters. + tag_id (str): + Required. "Tag ID to forward events to. Also + known as the Measurement ID, or the "G-ID" (For + example: G-12345). + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + tag_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DataRedactionSettings(proto.Message): + r"""Settings for client-side data redaction. Singleton resource + under a Web Stream. + + Attributes: + name (str): + Output only. Name of this Data Redaction Settings resource. + Format: + properties/{property_id}/dataStreams/{data_stream}/dataRedactionSettings + Example: + "properties/1000/dataStreams/2000/dataRedactionSettings". + email_redaction_enabled (bool): + If enabled, any event parameter or user + property values that look like an email will be + redacted. + query_parameter_redaction_enabled (bool): + Query Parameter redaction removes the key and value portions + of a query parameter if it is in the configured set of query + parameters. + + If enabled, URL query replacement logic will be run for the + Stream. Any query parameters defined in query_parameter_keys + will be redacted. + query_parameter_keys (MutableSequence[str]): + The query parameter keys to apply redaction logic to if + present in the URL. Query parameter matching is + case-insensitive. + + Must contain at least one element if + query_parameter_replacement_enabled is true. Keys cannot + contain commas. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + email_redaction_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + query_parameter_redaction_enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + query_parameter_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class AdSenseLink(proto.Message): + r"""A link between a GA4 Property and an AdSense for Content ad + client. + + Attributes: + name (str): + Output only. The resource name for this + AdSense Link resource. Format: + properties/{propertyId}/adSenseLinks/{linkId} + Example: properties/1234/adSenseLinks/6789 + ad_client_code (str): + Immutable. The AdSense ad client code that + the GA4 property is linked to. Example format: + "ca-pub-1234567890". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ad_client_code: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RollupPropertySourceLink(proto.Message): + r"""A link that references a source property under the parent + rollup property. + + Attributes: + name (str): + Output only. Resource name of this RollupPropertySourceLink. + Format: + 'properties/{property_id}/rollupPropertySourceLinks/{rollup_property_source_link}' + Format: 'properties/123/rollupPropertySourceLinks/456' + source_property (str): + Immutable. Resource name of the source property. Format: + properties/{property_id} Example: "properties/789". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + source_property: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/subproperty_event_filter.py b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/subproperty_event_filter.py new file mode 100644 index 000000000000..7e1bb0b8da2f --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/google/analytics/admin_v1alpha/types/subproperty_event_filter.py @@ -0,0 +1,285 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin.v1alpha', + manifest={ + 'SubpropertyEventFilterCondition', + 'SubpropertyEventFilterExpression', + 'SubpropertyEventFilterExpressionList', + 'SubpropertyEventFilterClause', + 'SubpropertyEventFilter', + }, +) + + +class SubpropertyEventFilterCondition(proto.Message): + r"""A specific filter expression + + 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: + null_filter (bool): + A filter for null values. + + This field is a member of `oneof`_ ``one_filter``. + string_filter (google.analytics.admin_v1alpha.types.SubpropertyEventFilterCondition.StringFilter): + A filter for a string-type dimension that + matches a particular pattern. + + This field is a member of `oneof`_ ``one_filter``. + field_name (str): + Required. The field that is being filtered. + """ + + class StringFilter(proto.Message): + r"""A filter for a string-type dimension that matches a + particular pattern. + + Attributes: + match_type (google.analytics.admin_v1alpha.types.SubpropertyEventFilterCondition.StringFilter.MatchType): + Required. The match type for the string + filter. + value (str): + Required. The string value used for the + matching. + case_sensitive (bool): + Optional. If true, the string value is case + sensitive. If false, the match is + case-insensitive. + """ + class MatchType(proto.Enum): + r"""How the filter will be used to determine a match. + + Values: + MATCH_TYPE_UNSPECIFIED (0): + Match type unknown or not specified. + EXACT (1): + Exact match of the string value. + BEGINS_WITH (2): + Begins with the string value. + ENDS_WITH (3): + Ends with the string value. + CONTAINS (4): + Contains the string value. + FULL_REGEXP (5): + Full regular expression matches with the + string value. + PARTIAL_REGEXP (6): + Partial regular expression matches with the + string value. + """ + MATCH_TYPE_UNSPECIFIED = 0 + EXACT = 1 + BEGINS_WITH = 2 + ENDS_WITH = 3 + CONTAINS = 4 + FULL_REGEXP = 5 + PARTIAL_REGEXP = 6 + + match_type: 'SubpropertyEventFilterCondition.StringFilter.MatchType' = proto.Field( + proto.ENUM, + number=1, + enum='SubpropertyEventFilterCondition.StringFilter.MatchType', + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=3, + ) + + null_filter: bool = proto.Field( + proto.BOOL, + number=2, + oneof='one_filter', + ) + string_filter: StringFilter = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_filter', + message=StringFilter, + ) + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SubpropertyEventFilterExpression(proto.Message): + r"""A logical expression of Subproperty event filters. + + 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: + or_group (google.analytics.admin_v1alpha.types.SubpropertyEventFilterExpressionList): + A list of expressions to OR’ed together. Must only contain + not_expression or filter_condition expressions. + + This field is a member of `oneof`_ ``expr``. + not_expression (google.analytics.admin_v1alpha.types.SubpropertyEventFilterExpression): + A filter expression to be NOT'ed (inverted, + complemented). It can only include a filter. + This cannot be set on the top level + SubpropertyEventFilterExpression. + + This field is a member of `oneof`_ ``expr``. + filter_condition (google.analytics.admin_v1alpha.types.SubpropertyEventFilterCondition): + Creates a filter that matches a specific + event. This cannot be set on the top level + SubpropertyEventFilterExpression. + + This field is a member of `oneof`_ ``expr``. + """ + + or_group: 'SubpropertyEventFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='expr', + message='SubpropertyEventFilterExpressionList', + ) + not_expression: 'SubpropertyEventFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + oneof='expr', + message='SubpropertyEventFilterExpression', + ) + filter_condition: 'SubpropertyEventFilterCondition' = proto.Field( + proto.MESSAGE, + number=3, + oneof='expr', + message='SubpropertyEventFilterCondition', + ) + + +class SubpropertyEventFilterExpressionList(proto.Message): + r"""A list of Subproperty event filter expressions. + + Attributes: + filter_expressions (MutableSequence[google.analytics.admin_v1alpha.types.SubpropertyEventFilterExpression]): + Required. Unordered list. A list of + Subproperty event filter expressions + """ + + filter_expressions: MutableSequence['SubpropertyEventFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SubpropertyEventFilterExpression', + ) + + +class SubpropertyEventFilterClause(proto.Message): + r"""A clause for defining a filter. A filter may be inclusive + (events satisfying the filter clause are included in the + subproperty's data) or exclusive (events satisfying the filter + clause are excluded from the subproperty's data). + + Attributes: + filter_clause_type (google.analytics.admin_v1alpha.types.SubpropertyEventFilterClause.FilterClauseType): + Required. The type for the filter clause. + filter_expression (google.analytics.admin_v1alpha.types.SubpropertyEventFilterExpression): + Required. The logical expression for what + events are sent to the subproperty. + """ + class FilterClauseType(proto.Enum): + r"""Specifies whether this is an include or exclude filter + clause. + + Values: + FILTER_CLAUSE_TYPE_UNSPECIFIED (0): + Filter clause type unknown or not specified. + INCLUDE (1): + Events will be included in the Sub property + if the filter clause is met. + EXCLUDE (2): + Events will be excluded from the Sub property + if the filter clause is met. + """ + FILTER_CLAUSE_TYPE_UNSPECIFIED = 0 + INCLUDE = 1 + EXCLUDE = 2 + + filter_clause_type: FilterClauseType = proto.Field( + proto.ENUM, + number=1, + enum=FilterClauseType, + ) + filter_expression: 'SubpropertyEventFilterExpression' = proto.Field( + proto.MESSAGE, + number=2, + message='SubpropertyEventFilterExpression', + ) + + +class SubpropertyEventFilter(proto.Message): + r"""A resource message representing a GA4 Subproperty event + filter. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Format: + properties/{ordinary_property_id}/subpropertyEventFilters/{sub_property_event_filter} + Example: properties/1234/subpropertyEventFilters/5678 + apply_to_property (str): + Immutable. Resource name of the Subproperty + that uses this filter. + + This field is a member of `oneof`_ ``_apply_to_property``. + filter_clauses (MutableSequence[google.analytics.admin_v1alpha.types.SubpropertyEventFilterClause]): + Required. Unordered list. Filter clauses that + define the SubpropertyEventFilter. All clauses + are AND'ed together to determine what data is + sent to the subproperty. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + apply_to_property: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + filter_clauses: MutableSequence['SubpropertyEventFilterClause'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='SubpropertyEventFilterClause', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/mypy.ini b/owl-bot-staging/google-analytics-admin/v1alpha/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/noxfile.py b/owl-bot-staging/google-analytics-admin/v1alpha/noxfile.py new file mode 100644 index 000000000000..7b5bf5e9f4ff --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-analytics-admin' + +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) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/analytics/admin_v1alpha/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + session.skip("cpp implementation is not supported in python 3.11+") + + # 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/analytics/admin_v1alpha/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-analytics-admin/v1alpha/scripts/fixup_admin_v1alpha_keywords.py b/owl-bot-staging/google-analytics-admin/v1alpha/scripts/fixup_admin_v1alpha_keywords.py new file mode 100644 index 000000000000..f64a22e0acb1 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/scripts/fixup_admin_v1alpha_keywords.py @@ -0,0 +1,325 @@ +#! /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 adminCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'acknowledge_user_data_collection': ('property', 'acknowledgement', ), + 'approve_display_video360_advertiser_link_proposal': ('name', ), + 'archive_audience': ('name', ), + 'archive_custom_dimension': ('name', ), + 'archive_custom_metric': ('name', ), + 'batch_create_access_bindings': ('parent', 'requests', ), + 'batch_delete_access_bindings': ('parent', 'requests', ), + 'batch_get_access_bindings': ('parent', 'names', ), + 'batch_update_access_bindings': ('parent', 'requests', ), + 'cancel_display_video360_advertiser_link_proposal': ('name', ), + 'create_access_binding': ('parent', 'access_binding', ), + 'create_ad_sense_link': ('parent', 'adsense_link', ), + 'create_audience': ('parent', 'audience', ), + 'create_big_query_link': ('parent', 'bigquery_link', ), + 'create_calculated_metric': ('parent', 'calculated_metric_id', 'calculated_metric', ), + 'create_channel_group': ('parent', 'channel_group', ), + 'create_connected_site_tag': ('connected_site_tag', 'property', ), + 'create_conversion_event': ('conversion_event', 'parent', ), + 'create_custom_dimension': ('parent', 'custom_dimension', ), + 'create_custom_metric': ('parent', 'custom_metric', ), + 'create_data_stream': ('parent', 'data_stream', ), + 'create_display_video360_advertiser_link': ('parent', 'display_video_360_advertiser_link', ), + 'create_display_video360_advertiser_link_proposal': ('parent', 'display_video_360_advertiser_link_proposal', ), + 'create_event_create_rule': ('parent', 'event_create_rule', ), + 'create_event_edit_rule': ('parent', 'event_edit_rule', ), + 'create_expanded_data_set': ('parent', 'expanded_data_set', ), + 'create_firebase_link': ('parent', 'firebase_link', ), + 'create_google_ads_link': ('parent', 'google_ads_link', ), + 'create_key_event': ('key_event', 'parent', ), + 'create_measurement_protocol_secret': ('parent', 'measurement_protocol_secret', ), + 'create_property': ('property', ), + 'create_rollup_property': ('rollup_property', 'source_properties', ), + 'create_rollup_property_source_link': ('parent', 'rollup_property_source_link', ), + 'create_search_ads360_link': ('parent', 'search_ads_360_link', ), + 'create_sk_ad_network_conversion_value_schema': ('parent', 'skadnetwork_conversion_value_schema', ), + 'create_subproperty_event_filter': ('parent', 'subproperty_event_filter', ), + 'delete_access_binding': ('name', ), + 'delete_account': ('name', ), + 'delete_ad_sense_link': ('name', ), + 'delete_big_query_link': ('name', ), + 'delete_calculated_metric': ('name', ), + 'delete_channel_group': ('name', ), + 'delete_connected_site_tag': ('property', 'tag_id', ), + 'delete_conversion_event': ('name', ), + 'delete_data_stream': ('name', ), + 'delete_display_video360_advertiser_link': ('name', ), + 'delete_display_video360_advertiser_link_proposal': ('name', ), + 'delete_event_create_rule': ('name', ), + 'delete_event_edit_rule': ('name', ), + 'delete_expanded_data_set': ('name', ), + 'delete_firebase_link': ('name', ), + 'delete_google_ads_link': ('name', ), + 'delete_key_event': ('name', ), + 'delete_measurement_protocol_secret': ('name', ), + 'delete_property': ('name', ), + 'delete_rollup_property_source_link': ('name', ), + 'delete_search_ads360_link': ('name', ), + 'delete_sk_ad_network_conversion_value_schema': ('name', ), + 'delete_subproperty_event_filter': ('name', ), + 'fetch_automated_ga4_configuration_opt_out': ('property', ), + 'fetch_connected_ga4_property': ('property', ), + 'get_access_binding': ('name', ), + 'get_account': ('name', ), + 'get_ad_sense_link': ('name', ), + 'get_attribution_settings': ('name', ), + 'get_audience': ('name', ), + 'get_big_query_link': ('name', ), + 'get_calculated_metric': ('name', ), + 'get_channel_group': ('name', ), + 'get_conversion_event': ('name', ), + 'get_custom_dimension': ('name', ), + 'get_custom_metric': ('name', ), + 'get_data_redaction_settings': ('name', ), + 'get_data_retention_settings': ('name', ), + 'get_data_sharing_settings': ('name', ), + 'get_data_stream': ('name', ), + 'get_display_video360_advertiser_link': ('name', ), + 'get_display_video360_advertiser_link_proposal': ('name', ), + 'get_enhanced_measurement_settings': ('name', ), + 'get_event_create_rule': ('name', ), + 'get_event_edit_rule': ('name', ), + 'get_expanded_data_set': ('name', ), + 'get_global_site_tag': ('name', ), + 'get_google_signals_settings': ('name', ), + 'get_key_event': ('name', ), + 'get_measurement_protocol_secret': ('name', ), + 'get_property': ('name', ), + 'get_rollup_property_source_link': ('name', ), + 'get_search_ads360_link': ('name', ), + 'get_sk_ad_network_conversion_value_schema': ('name', ), + 'get_subproperty_event_filter': ('name', ), + 'list_access_bindings': ('parent', 'page_size', 'page_token', ), + 'list_accounts': ('page_size', 'page_token', 'show_deleted', ), + 'list_account_summaries': ('page_size', 'page_token', ), + 'list_ad_sense_links': ('parent', 'page_size', 'page_token', ), + 'list_audiences': ('parent', 'page_size', 'page_token', ), + 'list_big_query_links': ('parent', 'page_size', 'page_token', ), + 'list_calculated_metrics': ('parent', 'page_size', 'page_token', ), + 'list_channel_groups': ('parent', 'page_size', 'page_token', ), + 'list_connected_site_tags': ('property', ), + 'list_conversion_events': ('parent', 'page_size', 'page_token', ), + 'list_custom_dimensions': ('parent', 'page_size', 'page_token', ), + 'list_custom_metrics': ('parent', 'page_size', 'page_token', ), + 'list_data_streams': ('parent', 'page_size', 'page_token', ), + 'list_display_video360_advertiser_link_proposals': ('parent', 'page_size', 'page_token', ), + 'list_display_video360_advertiser_links': ('parent', 'page_size', 'page_token', ), + 'list_event_create_rules': ('parent', 'page_size', 'page_token', ), + 'list_event_edit_rules': ('parent', 'page_size', 'page_token', ), + 'list_expanded_data_sets': ('parent', 'page_size', 'page_token', ), + 'list_firebase_links': ('parent', 'page_size', 'page_token', ), + 'list_google_ads_links': ('parent', 'page_size', 'page_token', ), + 'list_key_events': ('parent', 'page_size', 'page_token', ), + 'list_measurement_protocol_secrets': ('parent', 'page_size', 'page_token', ), + 'list_properties': ('filter', 'page_size', 'page_token', 'show_deleted', ), + 'list_rollup_property_source_links': ('parent', 'page_size', 'page_token', ), + 'list_search_ads360_links': ('parent', 'page_size', 'page_token', ), + 'list_sk_ad_network_conversion_value_schemas': ('parent', 'page_size', 'page_token', ), + 'list_subproperty_event_filters': ('parent', 'page_size', 'page_token', ), + 'provision_account_ticket': ('account', 'redirect_uri', ), + 'provision_subproperty': ('subproperty', 'subproperty_event_filter', ), + 'reorder_event_edit_rules': ('parent', 'event_edit_rules', ), + 'run_access_report': ('entity', 'dimensions', 'metrics', 'date_ranges', 'dimension_filter', 'metric_filter', 'offset', 'limit', 'time_zone', 'order_bys', 'return_entity_quota', 'include_all_users', 'expand_groups', ), + 'search_change_history_events': ('account', 'property', 'resource_type', 'action', 'actor_email', 'earliest_change_time', 'latest_change_time', 'page_size', 'page_token', ), + 'set_automated_ga4_configuration_opt_out': ('property', 'opt_out', ), + 'update_access_binding': ('access_binding', ), + 'update_account': ('account', 'update_mask', ), + 'update_attribution_settings': ('attribution_settings', 'update_mask', ), + 'update_audience': ('audience', 'update_mask', ), + 'update_big_query_link': ('bigquery_link', 'update_mask', ), + 'update_calculated_metric': ('calculated_metric', 'update_mask', ), + 'update_channel_group': ('channel_group', 'update_mask', ), + 'update_conversion_event': ('conversion_event', 'update_mask', ), + 'update_custom_dimension': ('update_mask', 'custom_dimension', ), + 'update_custom_metric': ('update_mask', 'custom_metric', ), + 'update_data_redaction_settings': ('data_redaction_settings', 'update_mask', ), + 'update_data_retention_settings': ('data_retention_settings', 'update_mask', ), + 'update_data_stream': ('update_mask', 'data_stream', ), + 'update_display_video360_advertiser_link': ('update_mask', 'display_video_360_advertiser_link', ), + 'update_enhanced_measurement_settings': ('enhanced_measurement_settings', 'update_mask', ), + 'update_event_create_rule': ('event_create_rule', 'update_mask', ), + 'update_event_edit_rule': ('event_edit_rule', 'update_mask', ), + 'update_expanded_data_set': ('expanded_data_set', 'update_mask', ), + 'update_google_ads_link': ('update_mask', 'google_ads_link', ), + 'update_google_signals_settings': ('google_signals_settings', 'update_mask', ), + 'update_key_event': ('key_event', 'update_mask', ), + 'update_measurement_protocol_secret': ('measurement_protocol_secret', 'update_mask', ), + 'update_property': ('property', 'update_mask', ), + 'update_search_ads360_link': ('update_mask', 'search_ads_360_link', ), + 'update_sk_ad_network_conversion_value_schema': ('skadnetwork_conversion_value_schema', 'update_mask', ), + 'update_subproperty_event_filter': ('subproperty_event_filter', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=adminCallTransformer(), +): + """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 admin 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-analytics-admin/v1alpha/setup.py b/owl-bot-staging/google-analytics-admin/v1alpha/setup.py new file mode 100644 index 000000000000..7caf4766b048 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/setup.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-analytics-admin' + + +description = "Google Analytics Admin API client library" + +version = None + +with open(os.path.join(package_root, 'google/analytics/admin/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.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-admin" + +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-analytics-admin/v1alpha/testing/constraints-3.10.txt b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.11.txt b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.12.txt b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.7.txt b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.20.2 diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.8.txt b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.9.txt b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1alpha/tests/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/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-analytics-admin/v1alpha/tests/unit/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/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-analytics-admin/v1alpha/tests/unit/gapic/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/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-analytics-admin/v1alpha/tests/unit/gapic/admin_v1alpha/__init__.py b/owl-bot-staging/google-analytics-admin/v1alpha/tests/unit/gapic/admin_v1alpha/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/tests/unit/gapic/admin_v1alpha/__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-analytics-admin/v1alpha/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py b/owl-bot-staging/google-analytics-admin/v1alpha/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py new file mode 100644 index 000000000000..690978c4fd79 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1alpha/tests/unit/gapic/admin_v1alpha/test_analytics_admin_service.py @@ -0,0 +1,102986 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1alpha.services.analytics_admin_service import AnalyticsAdminServiceAsyncClient +from google.analytics.admin_v1alpha.services.analytics_admin_service import AnalyticsAdminServiceClient +from google.analytics.admin_v1alpha.services.analytics_admin_service import pagers +from google.analytics.admin_v1alpha.services.analytics_admin_service import transports +from google.analytics.admin_v1alpha.types import access_report +from google.analytics.admin_v1alpha.types import analytics_admin +from google.analytics.admin_v1alpha.types import audience +from google.analytics.admin_v1alpha.types import audience as gaa_audience +from google.analytics.admin_v1alpha.types import channel_group +from google.analytics.admin_v1alpha.types import channel_group as gaa_channel_group +from google.analytics.admin_v1alpha.types import event_create_and_edit +from google.analytics.admin_v1alpha.types import expanded_data_set +from google.analytics.admin_v1alpha.types import expanded_data_set as gaa_expanded_data_set +from google.analytics.admin_v1alpha.types import resources +from google.analytics.admin_v1alpha.types import subproperty_event_filter +from google.analytics.admin_v1alpha.types import subproperty_event_filter as gaa_subproperty_event_filter +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.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_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 AnalyticsAdminServiceClient._get_default_mtls_endpoint(None) is None + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AnalyticsAdminServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AnalyticsAdminServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AnalyticsAdminServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AnalyticsAdminServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AnalyticsAdminServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._get_client_cert_source(None, False) is None + assert AnalyticsAdminServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AnalyticsAdminServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AnalyticsAdminServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + default_endpoint = AnalyticsAdminServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AnalyticsAdminServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AnalyticsAdminServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AnalyticsAdminServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + assert AnalyticsAdminServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AnalyticsAdminServiceClient._get_api_endpoint(None, None, default_universe, "always") == AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + assert AnalyticsAdminServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + assert AnalyticsAdminServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AnalyticsAdminServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AnalyticsAdminServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AnalyticsAdminServiceClient._get_universe_domain(None, None) == AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AnalyticsAdminServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "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", [ + (AnalyticsAdminServiceClient, "grpc"), + (AnalyticsAdminServiceAsyncClient, "grpc_asyncio"), + (AnalyticsAdminServiceClient, "rest"), +]) +def test_analytics_admin_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 == ( + 'analyticsadmin.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://analyticsadmin.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AnalyticsAdminServiceGrpcTransport, "grpc"), + (transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AnalyticsAdminServiceRestTransport, "rest"), +]) +def test_analytics_admin_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", [ + (AnalyticsAdminServiceClient, "grpc"), + (AnalyticsAdminServiceAsyncClient, "grpc_asyncio"), + (AnalyticsAdminServiceClient, "rest"), +]) +def test_analytics_admin_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 == ( + 'analyticsadmin.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://analyticsadmin.googleapis.com' + ) + + +def test_analytics_admin_service_client_get_transport_class(): + transport = AnalyticsAdminServiceClient.get_transport_class() + available_transports = [ + transports.AnalyticsAdminServiceGrpcTransport, + transports.AnalyticsAdminServiceRestTransport, + ] + assert transport in available_transports + + transport = AnalyticsAdminServiceClient.get_transport_class("grpc") + assert transport == transports.AnalyticsAdminServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc"), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest"), +]) +@mock.patch.object(AnalyticsAdminServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceAsyncClient)) +def test_analytics_admin_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(AnalyticsAdminServiceClient, '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(AnalyticsAdminServiceClient, '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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc", "true"), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc", "false"), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest", "true"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AnalyticsAdminServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_analytics_admin_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", [ + AnalyticsAdminServiceClient, AnalyticsAdminServiceAsyncClient +]) +@mock.patch.object(AnalyticsAdminServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnalyticsAdminServiceAsyncClient)) +def test_analytics_admin_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", [ + AnalyticsAdminServiceClient, AnalyticsAdminServiceAsyncClient +]) +@mock.patch.object(AnalyticsAdminServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceAsyncClient)) +def test_analytics_admin_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + default_endpoint = AnalyticsAdminServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AnalyticsAdminServiceClient._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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc"), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest"), +]) +def test_analytics_admin_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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc", grpc_helpers), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest", None), +]) +def test_analytics_admin_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_analytics_admin_service_client_client_options_from_dict(): + with mock.patch('google.analytics.admin_v1alpha.services.analytics_admin_service.transports.AnalyticsAdminServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AnalyticsAdminServiceClient( + 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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc", grpc_helpers), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_analytics_admin_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( + "analyticsadmin.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/analytics.edit', + 'https://www.googleapis.com/auth/analytics.manage.users', + 'https://www.googleapis.com/auth/analytics.manage.users.readonly', + 'https://www.googleapis.com/auth/analytics.readonly', +), + scopes=None, + default_host="analyticsadmin.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAccountRequest, + dict, +]) +def test_get_account(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + ) + response = client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + + +def test_get_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccountRequest() + + +def test_get_account_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetAccountRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccountRequest( + name='name_value', + ) + +def test_get_account_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account] = mock_rpc + request = {} + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_account_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 = AnalyticsAdminServiceAsyncClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + )) + response = await client.get_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccountRequest() + +@pytest.mark.asyncio +async def test_get_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_account] = mock_object + + request = {} + await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_account_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetAccountRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + )) + response = await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + + +@pytest.mark.asyncio +async def test_get_account_async_from_dict(): + await test_get_account_async(request_type=dict) + + +def test_get_account_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = resources.Account() + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_account_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account()) + await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_account_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_account( + 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_account_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_account( + analytics_admin.GetAccountRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_account_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_account( + 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_account_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_account( + analytics_admin.GetAccountRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccountsRequest, + dict, +]) +def test_list_accounts(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAccountsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_accounts_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_accounts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountsRequest() + + +def test_list_accounts_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccountsRequest( + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_accounts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountsRequest( + page_token='page_token_value', + ) + +def test_list_accounts_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_accounts] = mock_rpc + request = {} + client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accounts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_accounts_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 = AnalyticsAdminServiceAsyncClient( + 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_accounts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountsRequest() + +@pytest.mark.asyncio +async def test_list_accounts_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_accounts in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_accounts] = mock_object + + request = {} + await client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_accounts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_accounts_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListAccountsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_accounts_async_from_dict(): + await test_list_accounts_async(request_type=dict) + + +def test_list_accounts_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_accounts(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Account) + for i in results) +def test_list_accounts_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + RuntimeError, + ) + pages = list(client.list_accounts(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_accounts_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_accounts(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, resources.Account) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_accounts_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + 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_accounts(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", [ + analytics_admin.DeleteAccountRequest, + dict, +]) +def test_delete_account(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAccountRequest() + + +def test_delete_account_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteAccountRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAccountRequest( + name='name_value', + ) + +def test_delete_account_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_account] = mock_rpc + request = {} + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_account_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 = AnalyticsAdminServiceAsyncClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAccountRequest() + +@pytest.mark.asyncio +async def test_delete_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_account] = mock_object + + request = {} + await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_account_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteAccountRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteAccountRequest() + 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_account_async_from_dict(): + await test_delete_account_async(request_type=dict) + + +def test_delete_account_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = None + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_account_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_account_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__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_account( + 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_account_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_account( + analytics_admin.DeleteAccountRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_account_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__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_account( + 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_account_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_account( + analytics_admin.DeleteAccountRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAccountRequest, + dict, +]) +def test_update_account(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + ) + response = client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + + +def test_update_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAccountRequest() + + +def test_update_account_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateAccountRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAccountRequest( + ) + +def test_update_account_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + request = {} + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_account_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 = AnalyticsAdminServiceAsyncClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + )) + response = await client.update_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAccountRequest() + +@pytest.mark.asyncio +async def test_update_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_account] = mock_object + + request = {} + await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_account_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateAccountRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + )) + response = await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + + +@pytest.mark.asyncio +async def test_update_account_async_from_dict(): + await test_update_account_async(request_type=dict) + + +def test_update_account_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAccountRequest() + + request.account.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = resources.Account() + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'account.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_account_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAccountRequest() + + request.account.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account()) + await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'account.name=name_value', + ) in kw['metadata'] + + +def test_update_account_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_account( + account=resources.Account(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].account + mock_val = resources.Account(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_account_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_account( + analytics_admin.UpdateAccountRequest(), + account=resources.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_account_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_account( + account=resources.Account(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].account + mock_val = resources.Account(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_account_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_account( + analytics_admin.UpdateAccountRequest(), + account=resources.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ProvisionAccountTicketRequest, + dict, +]) +def test_provision_account_ticket(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_account_ticket), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ProvisionAccountTicketResponse( + account_ticket_id='account_ticket_id_value', + ) + response = client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ProvisionAccountTicketRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionAccountTicketResponse) + assert response.account_ticket_id == 'account_ticket_id_value' + + +def test_provision_account_ticket_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_account_ticket), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.provision_account_ticket() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionAccountTicketRequest() + + +def test_provision_account_ticket_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ProvisionAccountTicketRequest( + redirect_uri='redirect_uri_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_account_ticket), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.provision_account_ticket(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionAccountTicketRequest( + redirect_uri='redirect_uri_value', + ) + +def test_provision_account_ticket_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.provision_account_ticket in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.provision_account_ticket] = mock_rpc + request = {} + client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provision_account_ticket(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_provision_account_ticket_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 = AnalyticsAdminServiceAsyncClient( + 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.provision_account_ticket), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ProvisionAccountTicketResponse( + account_ticket_id='account_ticket_id_value', + )) + response = await client.provision_account_ticket() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionAccountTicketRequest() + +@pytest.mark.asyncio +async def test_provision_account_ticket_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.provision_account_ticket in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.provision_account_ticket] = mock_object + + request = {} + await client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.provision_account_ticket(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_provision_account_ticket_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ProvisionAccountTicketRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_account_ticket), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ProvisionAccountTicketResponse( + account_ticket_id='account_ticket_id_value', + )) + response = await client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ProvisionAccountTicketRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionAccountTicketResponse) + assert response.account_ticket_id == 'account_ticket_id_value' + + +@pytest.mark.asyncio +async def test_provision_account_ticket_async_from_dict(): + await test_provision_account_ticket_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccountSummariesRequest, + dict, +]) +def test_list_account_summaries(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account_summaries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAccountSummariesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccountSummariesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountSummariesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_account_summaries_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_account_summaries), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_account_summaries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountSummariesRequest() + + +def test_list_account_summaries_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccountSummariesRequest( + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_summaries), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_account_summaries(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountSummariesRequest( + page_token='page_token_value', + ) + +def test_list_account_summaries_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_account_summaries in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_account_summaries] = mock_rpc + request = {} + client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_summaries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_account_summaries_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 = AnalyticsAdminServiceAsyncClient( + 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_account_summaries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccountSummariesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_account_summaries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountSummariesRequest() + +@pytest.mark.asyncio +async def test_list_account_summaries_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_account_summaries in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_account_summaries] = mock_object + + request = {} + await client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_account_summaries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_account_summaries_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListAccountSummariesRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account_summaries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccountSummariesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccountSummariesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountSummariesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_account_summaries_async_from_dict(): + await test_list_account_summaries_async(request_type=dict) + + +def test_list_account_summaries_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_account_summaries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_account_summaries(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AccountSummary) + for i in results) +def test_list_account_summaries_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_account_summaries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + RuntimeError, + ) + pages = list(client.list_account_summaries(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_account_summaries_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_summaries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_account_summaries(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, resources.AccountSummary) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_account_summaries_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_summaries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + 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_account_summaries(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", [ + analytics_admin.GetPropertyRequest, + dict, +]) +def test_get_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + ) + response = client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetPropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +def test_get_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetPropertyRequest() + + +def test_get_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetPropertyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetPropertyRequest( + name='name_value', + ) + +def test_get_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_property] = mock_rpc + request = {} + client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_property_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 = AnalyticsAdminServiceAsyncClient( + 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.get_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetPropertyRequest() + +@pytest.mark.asyncio +async def test_get_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_property] = mock_object + + request = {} + await client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetPropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetPropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +@pytest.mark.asyncio +async def test_get_property_async_from_dict(): + await test_get_property_async(request_type=dict) + + +def test_get_property_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetPropertyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + call.return_value = resources.Property() + client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_property_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetPropertyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + await client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_property_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_property( + 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_property_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_property( + analytics_admin.GetPropertyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_property_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_property( + 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_property_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_property( + analytics_admin.GetPropertyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListPropertiesRequest, + dict, +]) +def test_list_properties(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListPropertiesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListPropertiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPropertiesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_properties_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_properties), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_properties() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListPropertiesRequest() + + +def test_list_properties_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListPropertiesRequest( + filter='filter_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_properties), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_properties(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListPropertiesRequest( + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_properties_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_properties in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_properties] = mock_rpc + request = {} + client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_properties(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_properties_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 = AnalyticsAdminServiceAsyncClient( + 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_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListPropertiesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_properties() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListPropertiesRequest() + +@pytest.mark.asyncio +async def test_list_properties_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_properties in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_properties] = mock_object + + request = {} + await client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_properties(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_properties_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListPropertiesRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListPropertiesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListPropertiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPropertiesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_properties_async_from_dict(): + await test_list_properties_async(request_type=dict) + + +def test_list_properties_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_properties), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_properties(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Property) + for i in results) +def test_list_properties_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_properties), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + RuntimeError, + ) + pages = list(client.list_properties(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_properties_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_properties), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_properties(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, resources.Property) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_properties_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_properties), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + 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_properties(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", [ + analytics_admin.CreatePropertyRequest, + dict, +]) +def test_create_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + ) + response = client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreatePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +def test_create_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreatePropertyRequest() + + +def test_create_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreatePropertyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreatePropertyRequest( + ) + +def test_create_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_property] = mock_rpc + request = {} + client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_property_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 = AnalyticsAdminServiceAsyncClient( + 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.create_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreatePropertyRequest() + +@pytest.mark.asyncio +async def test_create_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_property] = mock_object + + request = {} + await client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreatePropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreatePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +@pytest.mark.asyncio +async def test_create_property_async_from_dict(): + await test_create_property_async(request_type=dict) + + +def test_create_property_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_property( + property=resources.Property(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].property + mock_val = resources.Property(name='name_value') + assert arg == mock_val + + +def test_create_property_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_property( + analytics_admin.CreatePropertyRequest(), + property=resources.Property(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_property_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_property( + property=resources.Property(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].property + mock_val = resources.Property(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_property_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_property( + analytics_admin.CreatePropertyRequest(), + property=resources.Property(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeletePropertyRequest, + dict, +]) +def test_delete_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + ) + response = client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeletePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +def test_delete_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeletePropertyRequest() + + +def test_delete_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeletePropertyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeletePropertyRequest( + name='name_value', + ) + +def test_delete_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_property] = mock_rpc + request = {} + client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_property_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 = AnalyticsAdminServiceAsyncClient( + 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.delete_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeletePropertyRequest() + +@pytest.mark.asyncio +async def test_delete_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_property] = mock_object + + request = {} + await client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeletePropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeletePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +@pytest.mark.asyncio +async def test_delete_property_async_from_dict(): + await test_delete_property_async(request_type=dict) + + +def test_delete_property_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeletePropertyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + call.return_value = resources.Property() + client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_property_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeletePropertyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + await client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_property_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_property( + 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_property_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_property( + analytics_admin.DeletePropertyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_property_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_property( + 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_property_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_property( + analytics_admin.DeletePropertyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdatePropertyRequest, + dict, +]) +def test_update_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + ) + response = client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdatePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +def test_update_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdatePropertyRequest() + + +def test_update_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdatePropertyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdatePropertyRequest( + ) + +def test_update_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_property] = mock_rpc + request = {} + client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_property_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 = AnalyticsAdminServiceAsyncClient( + 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.update_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdatePropertyRequest() + +@pytest.mark.asyncio +async def test_update_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_property] = mock_object + + request = {} + await client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdatePropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdatePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +@pytest.mark.asyncio +async def test_update_property_async_from_dict(): + await test_update_property_async(request_type=dict) + + +def test_update_property_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdatePropertyRequest() + + request.property.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + call.return_value = resources.Property() + client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'property.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_property_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdatePropertyRequest() + + request.property.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + await client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'property.name=name_value', + ) in kw['metadata'] + + +def test_update_property_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_property( + property=resources.Property(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].property + mock_val = resources.Property(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_property_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_property( + analytics_admin.UpdatePropertyRequest(), + property=resources.Property(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_property_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_property( + property=resources.Property(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].property + mock_val = resources.Property(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_property_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_property( + analytics_admin.UpdatePropertyRequest(), + property=resources.Property(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateFirebaseLinkRequest, + dict, +]) +def test_create_firebase_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.FirebaseLink( + name='name_value', + project='project_value', + ) + response = client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateFirebaseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.FirebaseLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + + +def test_create_firebase_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_firebase_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_firebase_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateFirebaseLinkRequest() + + +def test_create_firebase_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateFirebaseLinkRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_firebase_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateFirebaseLinkRequest( + parent='parent_value', + ) + +def test_create_firebase_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_firebase_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_firebase_link] = mock_rpc + request = {} + client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_firebase_link_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 = AnalyticsAdminServiceAsyncClient( + 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.FirebaseLink( + name='name_value', + project='project_value', + )) + response = await client.create_firebase_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateFirebaseLinkRequest() + +@pytest.mark.asyncio +async def test_create_firebase_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_firebase_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_firebase_link] = mock_object + + request = {} + await client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_firebase_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateFirebaseLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.FirebaseLink( + name='name_value', + project='project_value', + )) + response = await client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateFirebaseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.FirebaseLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + + +@pytest.mark.asyncio +async def test_create_firebase_link_async_from_dict(): + await test_create_firebase_link_async(request_type=dict) + + +def test_create_firebase_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateFirebaseLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + call.return_value = resources.FirebaseLink() + client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateFirebaseLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.FirebaseLink()) + await client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.FirebaseLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_firebase_link( + parent='parent_value', + firebase_link=resources.FirebaseLink(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].firebase_link + mock_val = resources.FirebaseLink(name='name_value') + assert arg == mock_val + + +def test_create_firebase_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_firebase_link( + analytics_admin.CreateFirebaseLinkRequest(), + parent='parent_value', + firebase_link=resources.FirebaseLink(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_firebase_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.FirebaseLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.FirebaseLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_firebase_link( + parent='parent_value', + firebase_link=resources.FirebaseLink(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].firebase_link + mock_val = resources.FirebaseLink(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_firebase_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_firebase_link( + analytics_admin.CreateFirebaseLinkRequest(), + parent='parent_value', + firebase_link=resources.FirebaseLink(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteFirebaseLinkRequest, + dict, +]) +def test_delete_firebase_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteFirebaseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_firebase_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_firebase_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_firebase_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteFirebaseLinkRequest() + + +def test_delete_firebase_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteFirebaseLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_firebase_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteFirebaseLinkRequest( + name='name_value', + ) + +def test_delete_firebase_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_firebase_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_firebase_link] = mock_rpc + request = {} + client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_firebase_link_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 = AnalyticsAdminServiceAsyncClient( + 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_firebase_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteFirebaseLinkRequest() + +@pytest.mark.asyncio +async def test_delete_firebase_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_firebase_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_firebase_link] = mock_object + + request = {} + await client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_firebase_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteFirebaseLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteFirebaseLinkRequest() + 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_firebase_link_async_from_dict(): + await test_delete_firebase_link_async(request_type=dict) + + +def test_delete_firebase_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteFirebaseLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__call__') as call: + call.return_value = None + client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteFirebaseLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__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_firebase_link( + 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_firebase_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_firebase_link( + analytics_admin.DeleteFirebaseLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_firebase_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__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_firebase_link( + 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_firebase_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_firebase_link( + analytics_admin.DeleteFirebaseLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListFirebaseLinksRequest, + dict, +]) +def test_list_firebase_links(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListFirebaseLinksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListFirebaseLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirebaseLinksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_firebase_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_firebase_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_firebase_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListFirebaseLinksRequest() + + +def test_list_firebase_links_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListFirebaseLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_firebase_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListFirebaseLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_firebase_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_firebase_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_firebase_links] = mock_rpc + request = {} + client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_firebase_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_firebase_links_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 = AnalyticsAdminServiceAsyncClient( + 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_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListFirebaseLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_firebase_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListFirebaseLinksRequest() + +@pytest.mark.asyncio +async def test_list_firebase_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_firebase_links in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_firebase_links] = mock_object + + request = {} + await client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_firebase_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_firebase_links_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListFirebaseLinksRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListFirebaseLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListFirebaseLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirebaseLinksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_firebase_links_async_from_dict(): + await test_list_firebase_links_async(request_type=dict) + + +def test_list_firebase_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListFirebaseLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + call.return_value = analytics_admin.ListFirebaseLinksResponse() + client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListFirebaseLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListFirebaseLinksResponse()) + await client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListFirebaseLinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_firebase_links( + 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_firebase_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_firebase_links( + analytics_admin.ListFirebaseLinksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_firebase_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListFirebaseLinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListFirebaseLinksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_firebase_links( + 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_firebase_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_firebase_links( + analytics_admin.ListFirebaseLinksRequest(), + parent='parent_value', + ) + + +def test_list_firebase_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_firebase_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_firebase_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.FirebaseLink) + for i in results) +def test_list_firebase_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_firebase_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_firebase_links(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_firebase_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_firebase_links(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, resources.FirebaseLink) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_firebase_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + 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_firebase_links(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", [ + analytics_admin.GetGlobalSiteTagRequest, + dict, +]) +def test_get_global_site_tag(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_global_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GlobalSiteTag( + name='name_value', + snippet='snippet_value', + ) + response = client.get_global_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetGlobalSiteTagRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GlobalSiteTag) + assert response.name == 'name_value' + assert response.snippet == 'snippet_value' + + +def test_get_global_site_tag_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_global_site_tag), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_global_site_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetGlobalSiteTagRequest() + + +def test_get_global_site_tag_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetGlobalSiteTagRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_global_site_tag), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_global_site_tag(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetGlobalSiteTagRequest( + name='name_value', + ) + +def test_get_global_site_tag_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_global_site_tag in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_global_site_tag] = mock_rpc + request = {} + client.get_global_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_global_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_global_site_tag_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 = AnalyticsAdminServiceAsyncClient( + 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_global_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GlobalSiteTag( + name='name_value', + snippet='snippet_value', + )) + response = await client.get_global_site_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetGlobalSiteTagRequest() + +@pytest.mark.asyncio +async def test_get_global_site_tag_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_global_site_tag in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_global_site_tag] = mock_object + + request = {} + await client.get_global_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_global_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_global_site_tag_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetGlobalSiteTagRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_global_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.GlobalSiteTag( + name='name_value', + snippet='snippet_value', + )) + response = await client.get_global_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetGlobalSiteTagRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GlobalSiteTag) + assert response.name == 'name_value' + assert response.snippet == 'snippet_value' + + +@pytest.mark.asyncio +async def test_get_global_site_tag_async_from_dict(): + await test_get_global_site_tag_async(request_type=dict) + + +def test_get_global_site_tag_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetGlobalSiteTagRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_global_site_tag), + '__call__') as call: + call.return_value = resources.GlobalSiteTag() + client.get_global_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_global_site_tag_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetGlobalSiteTagRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_global_site_tag), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GlobalSiteTag()) + await client.get_global_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_global_site_tag_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_global_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GlobalSiteTag() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_global_site_tag( + 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_global_site_tag_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_global_site_tag( + analytics_admin.GetGlobalSiteTagRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_global_site_tag_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_global_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GlobalSiteTag() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GlobalSiteTag()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_global_site_tag( + 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_global_site_tag_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_global_site_tag( + analytics_admin.GetGlobalSiteTagRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateGoogleAdsLinkRequest, + dict, +]) +def test_create_google_ads_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + ) + response = client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + + +def test_create_google_ads_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateGoogleAdsLinkRequest() + + +def test_create_google_ads_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateGoogleAdsLinkRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_google_ads_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateGoogleAdsLinkRequest( + parent='parent_value', + ) + +def test_create_google_ads_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_google_ads_link] = mock_rpc + request = {} + client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_google_ads_link_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 = AnalyticsAdminServiceAsyncClient( + 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + )) + response = await client.create_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateGoogleAdsLinkRequest() + +@pytest.mark.asyncio +async def test_create_google_ads_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_google_ads_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_google_ads_link] = mock_object + + request = {} + await client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_google_ads_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateGoogleAdsLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + )) + response = await client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + + +@pytest.mark.asyncio +async def test_create_google_ads_link_async_from_dict(): + await test_create_google_ads_link_async(request_type=dict) + + +def test_create_google_ads_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateGoogleAdsLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + call.return_value = resources.GoogleAdsLink() + client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateGoogleAdsLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink()) + await client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_google_ads_link( + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(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].google_ads_link + mock_val = resources.GoogleAdsLink(name='name_value') + assert arg == mock_val + + +def test_create_google_ads_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link( + analytics_admin.CreateGoogleAdsLinkRequest(), + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_google_ads_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_google_ads_link( + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(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].google_ads_link + mock_val = resources.GoogleAdsLink(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_google_ads_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_ads_link( + analytics_admin.CreateGoogleAdsLinkRequest(), + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateGoogleAdsLinkRequest, + dict, +]) +def test_update_google_ads_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + ) + response = client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + + +def test_update_google_ads_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateGoogleAdsLinkRequest() + + +def test_update_google_ads_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateGoogleAdsLinkRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_google_ads_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateGoogleAdsLinkRequest( + ) + +def test_update_google_ads_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_google_ads_link] = mock_rpc + request = {} + client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_google_ads_link_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 = AnalyticsAdminServiceAsyncClient( + 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + )) + response = await client.update_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateGoogleAdsLinkRequest() + +@pytest.mark.asyncio +async def test_update_google_ads_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_google_ads_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_google_ads_link] = mock_object + + request = {} + await client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_google_ads_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateGoogleAdsLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + )) + response = await client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + + +@pytest.mark.asyncio +async def test_update_google_ads_link_async_from_dict(): + await test_update_google_ads_link_async(request_type=dict) + + +def test_update_google_ads_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateGoogleAdsLinkRequest() + + request.google_ads_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + call.return_value = resources.GoogleAdsLink() + client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_ads_link.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_google_ads_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateGoogleAdsLinkRequest() + + request.google_ads_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink()) + await client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_ads_link.name=name_value', + ) in kw['metadata'] + + +def test_update_google_ads_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_google_ads_link( + google_ads_link=resources.GoogleAdsLink(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].google_ads_link + mock_val = resources.GoogleAdsLink(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_google_ads_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link( + analytics_admin.UpdateGoogleAdsLinkRequest(), + google_ads_link=resources.GoogleAdsLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_google_ads_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_google_ads_link( + google_ads_link=resources.GoogleAdsLink(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].google_ads_link + mock_val = resources.GoogleAdsLink(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_google_ads_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_ads_link( + analytics_admin.UpdateGoogleAdsLinkRequest(), + google_ads_link=resources.GoogleAdsLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteGoogleAdsLinkRequest, + dict, +]) +def test_delete_google_ads_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_google_ads_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteGoogleAdsLinkRequest() + + +def test_delete_google_ads_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteGoogleAdsLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_google_ads_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteGoogleAdsLinkRequest( + name='name_value', + ) + +def test_delete_google_ads_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_google_ads_link] = mock_rpc + request = {} + client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_google_ads_link_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 = AnalyticsAdminServiceAsyncClient( + 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteGoogleAdsLinkRequest() + +@pytest.mark.asyncio +async def test_delete_google_ads_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_google_ads_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_google_ads_link] = mock_object + + request = {} + await client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_google_ads_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteGoogleAdsLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteGoogleAdsLinkRequest() + 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_google_ads_link_async_from_dict(): + await test_delete_google_ads_link_async(request_type=dict) + + +def test_delete_google_ads_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteGoogleAdsLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__call__') as call: + call.return_value = None + client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteGoogleAdsLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__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_google_ads_link( + 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_google_ads_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link( + analytics_admin.DeleteGoogleAdsLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_google_ads_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__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_google_ads_link( + 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_google_ads_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_ads_link( + analytics_admin.DeleteGoogleAdsLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListGoogleAdsLinksRequest, + dict, +]) +def test_list_google_ads_links(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListGoogleAdsLinksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListGoogleAdsLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleAdsLinksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_google_ads_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_google_ads_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListGoogleAdsLinksRequest() + + +def test_list_google_ads_links_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListGoogleAdsLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_google_ads_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListGoogleAdsLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_google_ads_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_google_ads_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_google_ads_links] = mock_rpc + request = {} + client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_google_ads_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_google_ads_links_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 = AnalyticsAdminServiceAsyncClient( + 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_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListGoogleAdsLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_google_ads_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListGoogleAdsLinksRequest() + +@pytest.mark.asyncio +async def test_list_google_ads_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_google_ads_links in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_google_ads_links] = mock_object + + request = {} + await client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_google_ads_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_google_ads_links_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListGoogleAdsLinksRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListGoogleAdsLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListGoogleAdsLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleAdsLinksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_google_ads_links_async_from_dict(): + await test_list_google_ads_links_async(request_type=dict) + + +def test_list_google_ads_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListGoogleAdsLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + call.return_value = analytics_admin.ListGoogleAdsLinksResponse() + client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListGoogleAdsLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListGoogleAdsLinksResponse()) + await client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListGoogleAdsLinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_google_ads_links( + 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_google_ads_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_links( + analytics_admin.ListGoogleAdsLinksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_google_ads_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListGoogleAdsLinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListGoogleAdsLinksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_google_ads_links( + 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_google_ads_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_ads_links( + analytics_admin.ListGoogleAdsLinksRequest(), + parent='parent_value', + ) + + +def test_list_google_ads_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_google_ads_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_google_ads_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.GoogleAdsLink) + for i in results) +def test_list_google_ads_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_google_ads_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_google_ads_links(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_google_ads_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_google_ads_links(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, resources.GoogleAdsLink) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_google_ads_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + 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_google_ads_links(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", [ + analytics_admin.GetDataSharingSettingsRequest, + dict, +]) +def test_get_data_sharing_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataSharingSettings( + name='name_value', + sharing_with_google_support_enabled=True, + sharing_with_google_assigned_sales_enabled=True, + sharing_with_google_any_sales_enabled=True, + sharing_with_google_products_enabled=True, + sharing_with_others_enabled=True, + ) + response = client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataSharingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataSharingSettings) + assert response.name == 'name_value' + assert response.sharing_with_google_support_enabled is True + assert response.sharing_with_google_assigned_sales_enabled is True + assert response.sharing_with_google_any_sales_enabled is True + assert response.sharing_with_google_products_enabled is True + assert response.sharing_with_others_enabled is True + + +def test_get_data_sharing_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_sharing_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataSharingSettingsRequest() + + +def test_get_data_sharing_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetDataSharingSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_sharing_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataSharingSettingsRequest( + name='name_value', + ) + +def test_get_data_sharing_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_sharing_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_sharing_settings] = mock_rpc + request = {} + client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_sharing_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataSharingSettings( + name='name_value', + sharing_with_google_support_enabled=True, + sharing_with_google_assigned_sales_enabled=True, + sharing_with_google_any_sales_enabled=True, + sharing_with_google_products_enabled=True, + sharing_with_others_enabled=True, + )) + response = await client.get_data_sharing_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataSharingSettingsRequest() + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_data_sharing_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_data_sharing_settings] = mock_object + + request = {} + await client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_data_sharing_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetDataSharingSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataSharingSettings( + name='name_value', + sharing_with_google_support_enabled=True, + sharing_with_google_assigned_sales_enabled=True, + sharing_with_google_any_sales_enabled=True, + sharing_with_google_products_enabled=True, + sharing_with_others_enabled=True, + )) + response = await client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataSharingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataSharingSettings) + assert response.name == 'name_value' + assert response.sharing_with_google_support_enabled is True + assert response.sharing_with_google_assigned_sales_enabled is True + assert response.sharing_with_google_any_sales_enabled is True + assert response.sharing_with_google_products_enabled is True + assert response.sharing_with_others_enabled is True + + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_async_from_dict(): + await test_get_data_sharing_settings_async(request_type=dict) + + +def test_get_data_sharing_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataSharingSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + call.return_value = resources.DataSharingSettings() + client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataSharingSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataSharingSettings()) + await client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_data_sharing_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataSharingSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_sharing_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_data_sharing_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_sharing_settings( + analytics_admin.GetDataSharingSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataSharingSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataSharingSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_sharing_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_sharing_settings( + analytics_admin.GetDataSharingSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetMeasurementProtocolSecretRequest, + dict, +]) +def test_get_measurement_protocol_secret(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + ) + response = client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +def test_get_measurement_protocol_secret_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetMeasurementProtocolSecretRequest() + + +def test_get_measurement_protocol_secret_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetMeasurementProtocolSecretRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_measurement_protocol_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetMeasurementProtocolSecretRequest( + name='name_value', + ) + +def test_get_measurement_protocol_secret_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_measurement_protocol_secret] = mock_rpc + request = {} + client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.get_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetMeasurementProtocolSecretRequest() + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_measurement_protocol_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_measurement_protocol_secret] = mock_object + + request = {} + await client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_async_from_dict(): + await test_get_measurement_protocol_secret_async(request_type=dict) + + +def test_get_measurement_protocol_secret_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetMeasurementProtocolSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + call.return_value = resources.MeasurementProtocolSecret() + client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetMeasurementProtocolSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + await client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_measurement_protocol_secret( + 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_measurement_protocol_secret_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret( + analytics_admin.GetMeasurementProtocolSecretRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_measurement_protocol_secret( + 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_measurement_protocol_secret_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secret( + analytics_admin.GetMeasurementProtocolSecretRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListMeasurementProtocolSecretsRequest, + dict, +]) +def test_list_measurement_protocol_secrets(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeasurementProtocolSecretsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_measurement_protocol_secrets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secrets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_measurement_protocol_secrets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListMeasurementProtocolSecretsRequest() + + +def test_list_measurement_protocol_secrets_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListMeasurementProtocolSecretsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_measurement_protocol_secrets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListMeasurementProtocolSecretsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_measurement_protocol_secrets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_measurement_protocol_secrets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_measurement_protocol_secrets] = mock_rpc + request = {} + client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_measurement_protocol_secrets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListMeasurementProtocolSecretsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_measurement_protocol_secrets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListMeasurementProtocolSecretsRequest() + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_measurement_protocol_secrets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_measurement_protocol_secrets] = mock_object + + request = {} + await client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_measurement_protocol_secrets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListMeasurementProtocolSecretsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListMeasurementProtocolSecretsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeasurementProtocolSecretsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_async_from_dict(): + await test_list_measurement_protocol_secrets_async(request_type=dict) + + +def test_list_measurement_protocol_secrets_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + call.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secrets_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListMeasurementProtocolSecretsResponse()) + await client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secrets_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_measurement_protocol_secrets( + 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_measurement_protocol_secrets_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secrets( + analytics_admin.ListMeasurementProtocolSecretsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListMeasurementProtocolSecretsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_measurement_protocol_secrets( + 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_measurement_protocol_secrets_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secrets( + analytics_admin.ListMeasurementProtocolSecretsRequest(), + parent='parent_value', + ) + + +def test_list_measurement_protocol_secrets_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secrets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_measurement_protocol_secrets(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.MeasurementProtocolSecret) + for i in results) +def test_list_measurement_protocol_secrets_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secrets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + RuntimeError, + ) + pages = list(client.list_measurement_protocol_secrets(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_measurement_protocol_secrets_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_measurement_protocol_secrets(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, resources.MeasurementProtocolSecret) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + 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_measurement_protocol_secrets(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", [ + analytics_admin.CreateMeasurementProtocolSecretRequest, + dict, +]) +def test_create_measurement_protocol_secret(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + ) + response = client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +def test_create_measurement_protocol_secret_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateMeasurementProtocolSecretRequest() + + +def test_create_measurement_protocol_secret_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateMeasurementProtocolSecretRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_measurement_protocol_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateMeasurementProtocolSecretRequest( + parent='parent_value', + ) + +def test_create_measurement_protocol_secret_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_measurement_protocol_secret] = mock_rpc + request = {} + client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.create_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateMeasurementProtocolSecretRequest() + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_measurement_protocol_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_measurement_protocol_secret] = mock_object + + request = {} + await client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_async_from_dict(): + await test_create_measurement_protocol_secret_async(request_type=dict) + + +def test_create_measurement_protocol_secret_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + call.return_value = resources.MeasurementProtocolSecret() + client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + await client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_measurement_protocol_secret( + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(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].measurement_protocol_secret + mock_val = resources.MeasurementProtocolSecret(name='name_value') + assert arg == mock_val + + +def test_create_measurement_protocol_secret_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret( + analytics_admin.CreateMeasurementProtocolSecretRequest(), + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_measurement_protocol_secret( + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(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].measurement_protocol_secret + mock_val = resources.MeasurementProtocolSecret(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secret( + analytics_admin.CreateMeasurementProtocolSecretRequest(), + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteMeasurementProtocolSecretRequest, + dict, +]) +def test_delete_measurement_protocol_secret(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_measurement_protocol_secret_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteMeasurementProtocolSecretRequest() + + +def test_delete_measurement_protocol_secret_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteMeasurementProtocolSecretRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_measurement_protocol_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteMeasurementProtocolSecretRequest( + name='name_value', + ) + +def test_delete_measurement_protocol_secret_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_measurement_protocol_secret] = mock_rpc + request = {} + client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_measurement_protocol_secret_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteMeasurementProtocolSecretRequest() + +@pytest.mark.asyncio +async def test_delete_measurement_protocol_secret_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_measurement_protocol_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_measurement_protocol_secret] = mock_object + + request = {} + await client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_measurement_protocol_secret_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteMeasurementProtocolSecretRequest() + 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_measurement_protocol_secret_async_from_dict(): + await test_delete_measurement_protocol_secret_async(request_type=dict) + + +def test_delete_measurement_protocol_secret_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteMeasurementProtocolSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__call__') as call: + call.return_value = None + client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteMeasurementProtocolSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__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_measurement_protocol_secret( + 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_measurement_protocol_secret_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret( + analytics_admin.DeleteMeasurementProtocolSecretRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_measurement_protocol_secret_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__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_measurement_protocol_secret( + 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_measurement_protocol_secret_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secret( + analytics_admin.DeleteMeasurementProtocolSecretRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateMeasurementProtocolSecretRequest, + dict, +]) +def test_update_measurement_protocol_secret(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + ) + response = client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +def test_update_measurement_protocol_secret_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateMeasurementProtocolSecretRequest() + + +def test_update_measurement_protocol_secret_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateMeasurementProtocolSecretRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_measurement_protocol_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateMeasurementProtocolSecretRequest( + ) + +def test_update_measurement_protocol_secret_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_measurement_protocol_secret] = mock_rpc + request = {} + client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.update_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateMeasurementProtocolSecretRequest() + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_measurement_protocol_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_measurement_protocol_secret] = mock_object + + request = {} + await client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_async_from_dict(): + await test_update_measurement_protocol_secret_async(request_type=dict) + + +def test_update_measurement_protocol_secret_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + + request.measurement_protocol_secret.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + call.return_value = resources.MeasurementProtocolSecret() + client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'measurement_protocol_secret.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + + request.measurement_protocol_secret.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + await client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'measurement_protocol_secret.name=name_value', + ) in kw['metadata'] + + +def test_update_measurement_protocol_secret_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_measurement_protocol_secret( + measurement_protocol_secret=resources.MeasurementProtocolSecret(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].measurement_protocol_secret + mock_val = resources.MeasurementProtocolSecret(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_measurement_protocol_secret_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret( + analytics_admin.UpdateMeasurementProtocolSecretRequest(), + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_measurement_protocol_secret( + measurement_protocol_secret=resources.MeasurementProtocolSecret(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].measurement_protocol_secret + mock_val = resources.MeasurementProtocolSecret(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_measurement_protocol_secret_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secret( + analytics_admin.UpdateMeasurementProtocolSecretRequest(), + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.AcknowledgeUserDataCollectionRequest, + dict, +]) +def test_acknowledge_user_data_collection(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.AcknowledgeUserDataCollectionResponse( + ) + response = client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.AcknowledgeUserDataCollectionResponse) + + +def test_acknowledge_user_data_collection_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.acknowledge_user_data_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.AcknowledgeUserDataCollectionRequest() + + +def test_acknowledge_user_data_collection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.AcknowledgeUserDataCollectionRequest( + property='property_value', + acknowledgement='acknowledgement_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.acknowledge_user_data_collection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.AcknowledgeUserDataCollectionRequest( + property='property_value', + acknowledgement='acknowledgement_value', + ) + +def test_acknowledge_user_data_collection_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.acknowledge_user_data_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.acknowledge_user_data_collection] = mock_rpc + request = {} + client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.acknowledge_user_data_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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.acknowledge_user_data_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.AcknowledgeUserDataCollectionResponse( + )) + response = await client.acknowledge_user_data_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.AcknowledgeUserDataCollectionRequest() + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.acknowledge_user_data_collection in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.acknowledge_user_data_collection] = mock_object + + request = {} + await client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.acknowledge_user_data_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.AcknowledgeUserDataCollectionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.AcknowledgeUserDataCollectionResponse( + )) + response = await client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.AcknowledgeUserDataCollectionResponse) + + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_async_from_dict(): + await test_acknowledge_user_data_collection_async(request_type=dict) + + +def test_acknowledge_user_data_collection_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + call.return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() + client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.AcknowledgeUserDataCollectionResponse()) + await client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, + dict, +]) +def test_get_sk_ad_network_conversion_value_schema(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=True, + ) + response = client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == 'name_value' + assert response.apply_conversion_values is True + + +def test_get_sk_ad_network_conversion_value_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_sk_ad_network_conversion_value_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() + + +def test_get_sk_ad_network_conversion_value_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_sk_ad_network_conversion_value_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSKAdNetworkConversionValueSchemaRequest( + name='name_value', + ) + +def test_get_sk_ad_network_conversion_value_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_sk_ad_network_conversion_value_schema] = mock_rpc + request = {} + client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_sk_ad_network_conversion_value_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=True, + )) + response = await client.get_sk_ad_network_conversion_value_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() + +@pytest.mark.asyncio +async def test_get_sk_ad_network_conversion_value_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_sk_ad_network_conversion_value_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_sk_ad_network_conversion_value_schema] = mock_object + + request = {} + await client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_sk_ad_network_conversion_value_schema_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetSKAdNetworkConversionValueSchemaRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=True, + )) + response = await client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == 'name_value' + assert response.apply_conversion_values is True + + +@pytest.mark.asyncio +async def test_get_sk_ad_network_conversion_value_schema_async_from_dict(): + await test_get_sk_ad_network_conversion_value_schema_async(request_type=dict) + + +def test_get_sk_ad_network_conversion_value_schema_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value = resources.SKAdNetworkConversionValueSchema() + client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_sk_ad_network_conversion_value_schema_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema()) + await client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_sk_ad_network_conversion_value_schema_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SKAdNetworkConversionValueSchema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_sk_ad_network_conversion_value_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_sk_ad_network_conversion_value_schema_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schema( + analytics_admin.GetSKAdNetworkConversionValueSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_sk_ad_network_conversion_value_schema_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SKAdNetworkConversionValueSchema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_sk_ad_network_conversion_value_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_sk_ad_network_conversion_value_schema_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_sk_ad_network_conversion_value_schema( + analytics_admin.GetSKAdNetworkConversionValueSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, + dict, +]) +def test_create_sk_ad_network_conversion_value_schema(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=True, + ) + response = client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == 'name_value' + assert response.apply_conversion_values is True + + +def test_create_sk_ad_network_conversion_value_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_sk_ad_network_conversion_value_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() + + +def test_create_sk_ad_network_conversion_value_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_sk_ad_network_conversion_value_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest( + parent='parent_value', + ) + +def test_create_sk_ad_network_conversion_value_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_sk_ad_network_conversion_value_schema] = mock_rpc + request = {} + client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_sk_ad_network_conversion_value_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=True, + )) + response = await client.create_sk_ad_network_conversion_value_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() + +@pytest.mark.asyncio +async def test_create_sk_ad_network_conversion_value_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_sk_ad_network_conversion_value_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_sk_ad_network_conversion_value_schema] = mock_object + + request = {} + await client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_sk_ad_network_conversion_value_schema_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=True, + )) + response = await client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == 'name_value' + assert response.apply_conversion_values is True + + +@pytest.mark.asyncio +async def test_create_sk_ad_network_conversion_value_schema_async_from_dict(): + await test_create_sk_ad_network_conversion_value_schema_async(request_type=dict) + + +def test_create_sk_ad_network_conversion_value_schema_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value = resources.SKAdNetworkConversionValueSchema() + client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_sk_ad_network_conversion_value_schema_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema()) + await client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_sk_ad_network_conversion_value_schema_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SKAdNetworkConversionValueSchema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_sk_ad_network_conversion_value_schema( + parent='parent_value', + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(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].skadnetwork_conversion_value_schema + mock_val = resources.SKAdNetworkConversionValueSchema(name='name_value') + assert arg == mock_val + + +def test_create_sk_ad_network_conversion_value_schema_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schema( + analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest(), + parent='parent_value', + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_sk_ad_network_conversion_value_schema_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SKAdNetworkConversionValueSchema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_sk_ad_network_conversion_value_schema( + parent='parent_value', + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(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].skadnetwork_conversion_value_schema + mock_val = resources.SKAdNetworkConversionValueSchema(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_sk_ad_network_conversion_value_schema_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_sk_ad_network_conversion_value_schema( + analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest(), + parent='parent_value', + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, + dict, +]) +def test_delete_sk_ad_network_conversion_value_schema(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sk_ad_network_conversion_value_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_sk_ad_network_conversion_value_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() + + +def test_delete_sk_ad_network_conversion_value_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_sk_ad_network_conversion_value_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest( + name='name_value', + ) + +def test_delete_sk_ad_network_conversion_value_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_sk_ad_network_conversion_value_schema] = mock_rpc + request = {} + client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_sk_ad_network_conversion_value_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sk_ad_network_conversion_value_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() + +@pytest.mark.asyncio +async def test_delete_sk_ad_network_conversion_value_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_sk_ad_network_conversion_value_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_sk_ad_network_conversion_value_schema] = mock_object + + request = {} + await client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_sk_ad_network_conversion_value_schema_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() + 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_sk_ad_network_conversion_value_schema_async_from_dict(): + await test_delete_sk_ad_network_conversion_value_schema_async(request_type=dict) + + +def test_delete_sk_ad_network_conversion_value_schema_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value = None + client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_sk_ad_network_conversion_value_schema_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_sk_ad_network_conversion_value_schema_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_sk_ad_network_conversion_value_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_sk_ad_network_conversion_value_schema_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schema( + analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_sk_ad_network_conversion_value_schema_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_sk_ad_network_conversion_value_schema( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_sk_ad_network_conversion_value_schema_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_sk_ad_network_conversion_value_schema( + analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, + dict, +]) +def test_update_sk_ad_network_conversion_value_schema(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=True, + ) + response = client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == 'name_value' + assert response.apply_conversion_values is True + + +def test_update_sk_ad_network_conversion_value_schema_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_sk_ad_network_conversion_value_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() + + +def test_update_sk_ad_network_conversion_value_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_sk_ad_network_conversion_value_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest( + ) + +def test_update_sk_ad_network_conversion_value_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_sk_ad_network_conversion_value_schema] = mock_rpc + request = {} + client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_sk_ad_network_conversion_value_schema_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=True, + )) + response = await client.update_sk_ad_network_conversion_value_schema() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() + +@pytest.mark.asyncio +async def test_update_sk_ad_network_conversion_value_schema_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_sk_ad_network_conversion_value_schema in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_sk_ad_network_conversion_value_schema] = mock_object + + request = {} + await client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_sk_ad_network_conversion_value_schema_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=True, + )) + response = await client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == 'name_value' + assert response.apply_conversion_values is True + + +@pytest.mark.asyncio +async def test_update_sk_ad_network_conversion_value_schema_async_from_dict(): + await test_update_sk_ad_network_conversion_value_schema_async(request_type=dict) + + +def test_update_sk_ad_network_conversion_value_schema_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() + + request.skadnetwork_conversion_value_schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value = resources.SKAdNetworkConversionValueSchema() + client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'skadnetwork_conversion_value_schema.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_sk_ad_network_conversion_value_schema_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() + + request.skadnetwork_conversion_value_schema.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sk_ad_network_conversion_value_schema), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema()) + await client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'skadnetwork_conversion_value_schema.name=name_value', + ) in kw['metadata'] + + +def test_update_sk_ad_network_conversion_value_schema_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SKAdNetworkConversionValueSchema() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_sk_ad_network_conversion_value_schema( + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(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].skadnetwork_conversion_value_schema + mock_val = resources.SKAdNetworkConversionValueSchema(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_sk_ad_network_conversion_value_schema_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schema( + analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest(), + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_sk_ad_network_conversion_value_schema_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_sk_ad_network_conversion_value_schema), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SKAdNetworkConversionValueSchema() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SKAdNetworkConversionValueSchema()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_sk_ad_network_conversion_value_schema( + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(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].skadnetwork_conversion_value_schema + mock_val = resources.SKAdNetworkConversionValueSchema(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_sk_ad_network_conversion_value_schema_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_sk_ad_network_conversion_value_schema( + analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest(), + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, + dict, +]) +def test_list_sk_ad_network_conversion_value_schemas(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + next_page_token='next_page_token_value', + ) + response = client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSKAdNetworkConversionValueSchemasPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_sk_ad_network_conversion_value_schemas_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schemas), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sk_ad_network_conversion_value_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() + + +def test_list_sk_ad_network_conversion_value_schemas_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sk_ad_network_conversion_value_schemas), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_sk_ad_network_conversion_value_schemas(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSKAdNetworkConversionValueSchemasRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_sk_ad_network_conversion_value_schemas_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_sk_ad_network_conversion_value_schemas in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_sk_ad_network_conversion_value_schemas] = mock_rpc + request = {} + client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sk_ad_network_conversion_value_schemas_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_sk_ad_network_conversion_value_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sk_ad_network_conversion_value_schemas() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() + +@pytest.mark.asyncio +async def test_list_sk_ad_network_conversion_value_schemas_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_sk_ad_network_conversion_value_schemas in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_sk_ad_network_conversion_value_schemas] = mock_object + + request = {} + await client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_sk_ad_network_conversion_value_schemas_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListSKAdNetworkConversionValueSchemasRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_sk_ad_network_conversion_value_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSKAdNetworkConversionValueSchemasAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_sk_ad_network_conversion_value_schemas_async_from_dict(): + await test_list_sk_ad_network_conversion_value_schemas_async(request_type=dict) + + +def test_list_sk_ad_network_conversion_value_schemas_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sk_ad_network_conversion_value_schemas), + '__call__') as call: + call.return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_sk_ad_network_conversion_value_schemas_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sk_ad_network_conversion_value_schemas), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSKAdNetworkConversionValueSchemasResponse()) + await client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_sk_ad_network_conversion_value_schemas_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sk_ad_network_conversion_value_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sk_ad_network_conversion_value_schemas( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_sk_ad_network_conversion_value_schemas_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_sk_ad_network_conversion_value_schemas( + analytics_admin.ListSKAdNetworkConversionValueSchemasRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_sk_ad_network_conversion_value_schemas_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sk_ad_network_conversion_value_schemas), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSKAdNetworkConversionValueSchemasResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sk_ad_network_conversion_value_schemas( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_sk_ad_network_conversion_value_schemas_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_sk_ad_network_conversion_value_schemas( + analytics_admin.ListSKAdNetworkConversionValueSchemasRequest(), + parent='parent_value', + ) + + +def test_list_sk_ad_network_conversion_value_schemas_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_sk_ad_network_conversion_value_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='abc', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[], + next_page_token='def', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_sk_ad_network_conversion_value_schemas(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SKAdNetworkConversionValueSchema) + for i in results) +def test_list_sk_ad_network_conversion_value_schemas_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_sk_ad_network_conversion_value_schemas), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='abc', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[], + next_page_token='def', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sk_ad_network_conversion_value_schemas(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_sk_ad_network_conversion_value_schemas_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sk_ad_network_conversion_value_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='abc', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[], + next_page_token='def', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sk_ad_network_conversion_value_schemas(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.SKAdNetworkConversionValueSchema) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_sk_ad_network_conversion_value_schemas_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sk_ad_network_conversion_value_schemas), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='abc', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[], + next_page_token='def', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + ), + 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_sk_ad_network_conversion_value_schemas(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + analytics_admin.SearchChangeHistoryEventsRequest, + dict, +]) +def test_search_change_history_events(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.SearchChangeHistoryEventsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.SearchChangeHistoryEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchChangeHistoryEventsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_change_history_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_change_history_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.SearchChangeHistoryEventsRequest() + + +def test_search_change_history_events_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.SearchChangeHistoryEventsRequest( + account='account_value', + property='property_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_change_history_events(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.SearchChangeHistoryEventsRequest( + account='account_value', + property='property_value', + page_token='page_token_value', + ) + +def test_search_change_history_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_change_history_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_change_history_events] = mock_rpc + request = {} + client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_change_history_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_change_history_events_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.SearchChangeHistoryEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_change_history_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.SearchChangeHistoryEventsRequest() + +@pytest.mark.asyncio +async def test_search_change_history_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.search_change_history_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.search_change_history_events] = mock_object + + request = {} + await client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.search_change_history_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_search_change_history_events_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.SearchChangeHistoryEventsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.SearchChangeHistoryEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.SearchChangeHistoryEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchChangeHistoryEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_change_history_events_async_from_dict(): + await test_search_change_history_events_async(request_type=dict) + + +def test_search_change_history_events_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.SearchChangeHistoryEventsRequest() + + request.account = 'account_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + call.return_value = analytics_admin.SearchChangeHistoryEventsResponse() + client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'account=account_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_change_history_events_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.SearchChangeHistoryEventsRequest() + + request.account = 'account_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.SearchChangeHistoryEventsResponse()) + await client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'account=account_value', + ) in kw['metadata'] + + +def test_search_change_history_events_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('account', ''), + )), + ) + pager = client.search_change_history_events(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ChangeHistoryEvent) + for i in results) +def test_search_change_history_events_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.search_change_history_events(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_change_history_events_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_change_history_events(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.ChangeHistoryEvent) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_change_history_events_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_change_history_events(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetGoogleSignalsSettingsRequest, + dict, +]) +def test_get_google_signals_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleSignalsSettings( + name='name_value', + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + ) + response = client.get_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetGoogleSignalsSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleSignalsSettings) + assert response.name == 'name_value' + assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED + assert response.consent == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED + + +def test_get_google_signals_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_signals_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_google_signals_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetGoogleSignalsSettingsRequest() + + +def test_get_google_signals_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetGoogleSignalsSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_signals_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_google_signals_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetGoogleSignalsSettingsRequest( + name='name_value', + ) + +def test_get_google_signals_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_google_signals_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_google_signals_settings] = mock_rpc + request = {} + client.get_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_signals_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_google_signals_settings_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 = AnalyticsAdminServiceAsyncClient( + 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_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleSignalsSettings( + name='name_value', + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + )) + response = await client.get_google_signals_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetGoogleSignalsSettingsRequest() + +@pytest.mark.asyncio +async def test_get_google_signals_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_google_signals_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_google_signals_settings] = mock_object + + request = {} + await client.get_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_google_signals_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_google_signals_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetGoogleSignalsSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleSignalsSettings( + name='name_value', + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + )) + response = await client.get_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetGoogleSignalsSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleSignalsSettings) + assert response.name == 'name_value' + assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED + assert response.consent == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED + + +@pytest.mark.asyncio +async def test_get_google_signals_settings_async_from_dict(): + await test_get_google_signals_settings_async(request_type=dict) + + +def test_get_google_signals_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetGoogleSignalsSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_signals_settings), + '__call__') as call: + call.return_value = resources.GoogleSignalsSettings() + client.get_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_signals_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetGoogleSignalsSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_signals_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleSignalsSettings()) + await client.get_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_signals_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleSignalsSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_google_signals_settings( + 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_google_signals_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_signals_settings( + analytics_admin.GetGoogleSignalsSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_google_signals_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleSignalsSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleSignalsSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_google_signals_settings( + 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_google_signals_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_signals_settings( + analytics_admin.GetGoogleSignalsSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateGoogleSignalsSettingsRequest, + dict, +]) +def test_update_google_signals_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleSignalsSettings( + name='name_value', + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + ) + response = client.update_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateGoogleSignalsSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleSignalsSettings) + assert response.name == 'name_value' + assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED + assert response.consent == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED + + +def test_update_google_signals_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_signals_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_google_signals_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateGoogleSignalsSettingsRequest() + + +def test_update_google_signals_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateGoogleSignalsSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_signals_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_google_signals_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateGoogleSignalsSettingsRequest( + ) + +def test_update_google_signals_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_google_signals_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_google_signals_settings] = mock_rpc + request = {} + client.update_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_google_signals_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_google_signals_settings_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 = AnalyticsAdminServiceAsyncClient( + 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_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleSignalsSettings( + name='name_value', + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + )) + response = await client.update_google_signals_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateGoogleSignalsSettingsRequest() + +@pytest.mark.asyncio +async def test_update_google_signals_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_google_signals_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_google_signals_settings] = mock_object + + request = {} + await client.update_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_google_signals_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_google_signals_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateGoogleSignalsSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleSignalsSettings( + name='name_value', + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + )) + response = await client.update_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateGoogleSignalsSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleSignalsSettings) + assert response.name == 'name_value' + assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED + assert response.consent == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED + + +@pytest.mark.asyncio +async def test_update_google_signals_settings_async_from_dict(): + await test_update_google_signals_settings_async(request_type=dict) + + +def test_update_google_signals_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateGoogleSignalsSettingsRequest() + + request.google_signals_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_signals_settings), + '__call__') as call: + call.return_value = resources.GoogleSignalsSettings() + client.update_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_signals_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_google_signals_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateGoogleSignalsSettingsRequest() + + request.google_signals_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_signals_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleSignalsSettings()) + await client.update_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_signals_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_google_signals_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleSignalsSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_google_signals_settings( + google_signals_settings=resources.GoogleSignalsSettings(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].google_signals_settings + mock_val = resources.GoogleSignalsSettings(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_google_signals_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_signals_settings( + analytics_admin.UpdateGoogleSignalsSettingsRequest(), + google_signals_settings=resources.GoogleSignalsSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_google_signals_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_signals_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleSignalsSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleSignalsSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_google_signals_settings( + google_signals_settings=resources.GoogleSignalsSettings(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].google_signals_settings + mock_val = resources.GoogleSignalsSettings(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_google_signals_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_signals_settings( + analytics_admin.UpdateGoogleSignalsSettingsRequest(), + google_signals_settings=resources.GoogleSignalsSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateConversionEventRequest, + dict, +]) +def test_create_conversion_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + response = client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +def test_create_conversion_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateConversionEventRequest() + + +def test_create_conversion_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateConversionEventRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_conversion_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateConversionEventRequest( + parent='parent_value', + ) + +def test_create_conversion_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_conversion_event] = mock_rpc + request = {} + client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_conversion_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.create_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateConversionEventRequest() + +@pytest.mark.asyncio +async def test_create_conversion_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_conversion_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_conversion_event] = mock_object + + request = {} + await client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_conversion_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateConversionEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_create_conversion_event_async_from_dict(): + await test_create_conversion_event_async(request_type=dict) + + +def test_create_conversion_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateConversionEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + call.return_value = resources.ConversionEvent() + client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_conversion_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateConversionEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + await client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_conversion_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversion_event( + parent='parent_value', + conversion_event=resources.ConversionEvent(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].conversion_event + mock_val = resources.ConversionEvent(name='name_value') + assert arg == mock_val + + +def test_create_conversion_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event( + analytics_admin.CreateConversionEventRequest(), + parent='parent_value', + conversion_event=resources.ConversionEvent(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_conversion_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversion_event( + parent='parent_value', + conversion_event=resources.ConversionEvent(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].conversion_event + mock_val = resources.ConversionEvent(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_conversion_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_event( + analytics_admin.CreateConversionEventRequest(), + parent='parent_value', + conversion_event=resources.ConversionEvent(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateConversionEventRequest, + dict, +]) +def test_update_conversion_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + response = client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +def test_update_conversion_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateConversionEventRequest() + + +def test_update_conversion_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateConversionEventRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_conversion_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateConversionEventRequest( + ) + +def test_update_conversion_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_conversion_event] = mock_rpc + request = {} + client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_conversion_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.update_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateConversionEventRequest() + +@pytest.mark.asyncio +async def test_update_conversion_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_conversion_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_conversion_event] = mock_object + + request = {} + await client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_conversion_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateConversionEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_update_conversion_event_async_from_dict(): + await test_update_conversion_event_async(request_type=dict) + + +def test_update_conversion_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateConversionEventRequest() + + request.conversion_event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + call.return_value = resources.ConversionEvent() + client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'conversion_event.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_conversion_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateConversionEventRequest() + + request.conversion_event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + await client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'conversion_event.name=name_value', + ) in kw['metadata'] + + +def test_update_conversion_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversion_event( + conversion_event=resources.ConversionEvent(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].conversion_event + mock_val = resources.ConversionEvent(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_conversion_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event( + analytics_admin.UpdateConversionEventRequest(), + conversion_event=resources.ConversionEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_conversion_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_conversion_event( + conversion_event=resources.ConversionEvent(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].conversion_event + mock_val = resources.ConversionEvent(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_conversion_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_event( + analytics_admin.UpdateConversionEventRequest(), + conversion_event=resources.ConversionEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetConversionEventRequest, + dict, +]) +def test_get_conversion_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + response = client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +def test_get_conversion_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetConversionEventRequest() + + +def test_get_conversion_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetConversionEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_conversion_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetConversionEventRequest( + name='name_value', + ) + +def test_get_conversion_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_conversion_event] = mock_rpc + request = {} + client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_conversion_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.get_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetConversionEventRequest() + +@pytest.mark.asyncio +async def test_get_conversion_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_conversion_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_conversion_event] = mock_object + + request = {} + await client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_conversion_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetConversionEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_get_conversion_event_async_from_dict(): + await test_get_conversion_event_async(request_type=dict) + + +def test_get_conversion_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetConversionEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + call.return_value = resources.ConversionEvent() + client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_conversion_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetConversionEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + await client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_conversion_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversion_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_conversion_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event( + analytics_admin.GetConversionEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_conversion_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversion_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_conversion_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_event( + analytics_admin.GetConversionEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteConversionEventRequest, + dict, +]) +def test_delete_conversion_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversion_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConversionEventRequest() + + +def test_delete_conversion_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteConversionEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_conversion_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConversionEventRequest( + name='name_value', + ) + +def test_delete_conversion_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_conversion_event] = mock_rpc + request = {} + client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_conversion_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConversionEventRequest() + +@pytest.mark.asyncio +async def test_delete_conversion_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_conversion_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_conversion_event] = mock_object + + request = {} + await client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_conversion_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteConversionEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteConversionEventRequest() + 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_conversion_event_async_from_dict(): + await test_delete_conversion_event_async(request_type=dict) + + +def test_delete_conversion_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteConversionEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__call__') as call: + call.return_value = None + client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_conversion_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteConversionEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_conversion_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__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_conversion_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_conversion_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event( + analytics_admin.DeleteConversionEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_conversion_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__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_conversion_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_conversion_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_event( + analytics_admin.DeleteConversionEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListConversionEventsRequest, + dict, +]) +def test_list_conversion_events(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListConversionEventsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListConversionEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversionEventsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversion_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_conversion_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListConversionEventsRequest() + + +def test_list_conversion_events_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListConversionEventsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_conversion_events(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListConversionEventsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_conversion_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_conversion_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_conversion_events] = mock_rpc + request = {} + client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conversion_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_conversion_events_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConversionEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversion_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListConversionEventsRequest() + +@pytest.mark.asyncio +async def test_list_conversion_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_conversion_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_conversion_events] = mock_object + + request = {} + await client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_conversion_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_conversion_events_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListConversionEventsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConversionEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListConversionEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversionEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversion_events_async_from_dict(): + await test_list_conversion_events_async(request_type=dict) + + +def test_list_conversion_events_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListConversionEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + call.return_value = analytics_admin.ListConversionEventsResponse() + client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_conversion_events_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListConversionEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConversionEventsResponse()) + await client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_conversion_events_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListConversionEventsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversion_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_conversion_events_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_events( + analytics_admin.ListConversionEventsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_conversion_events_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListConversionEventsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConversionEventsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversion_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_conversion_events_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_events( + analytics_admin.ListConversionEventsRequest(), + parent='parent_value', + ) + + +def test_list_conversion_events_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_conversion_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversion_events(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ConversionEvent) + for i in results) +def test_list_conversion_events_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_conversion_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversion_events(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_conversion_events_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversion_events(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.ConversionEvent) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_conversion_events_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + 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_conversion_events(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateKeyEventRequest, + dict, +]) +def test_create_key_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + response = client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +def test_create_key_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateKeyEventRequest() + + +def test_create_key_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateKeyEventRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_key_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateKeyEventRequest( + parent='parent_value', + ) + +def test_create_key_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_key_event] = mock_rpc + request = {} + client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_key_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.create_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateKeyEventRequest() + +@pytest.mark.asyncio +async def test_create_key_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_key_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_key_event] = mock_object + + request = {} + await client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_key_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateKeyEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_create_key_event_async_from_dict(): + await test_create_key_event_async(request_type=dict) + + +def test_create_key_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateKeyEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + call.return_value = resources.KeyEvent() + client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_key_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateKeyEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + await client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_key_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_key_event( + parent='parent_value', + key_event=resources.KeyEvent(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].key_event + mock_val = resources.KeyEvent(name='name_value') + assert arg == mock_val + + +def test_create_key_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_event( + analytics_admin.CreateKeyEventRequest(), + parent='parent_value', + key_event=resources.KeyEvent(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_key_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_key_event( + parent='parent_value', + key_event=resources.KeyEvent(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].key_event + mock_val = resources.KeyEvent(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_key_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_event( + analytics_admin.CreateKeyEventRequest(), + parent='parent_value', + key_event=resources.KeyEvent(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateKeyEventRequest, + dict, +]) +def test_update_key_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + response = client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +def test_update_key_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateKeyEventRequest() + + +def test_update_key_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateKeyEventRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_key_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateKeyEventRequest( + ) + +def test_update_key_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_key_event] = mock_rpc + request = {} + client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_key_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.update_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateKeyEventRequest() + +@pytest.mark.asyncio +async def test_update_key_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_key_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_key_event] = mock_object + + request = {} + await client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_key_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateKeyEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_update_key_event_async_from_dict(): + await test_update_key_event_async(request_type=dict) + + +def test_update_key_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateKeyEventRequest() + + request.key_event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + call.return_value = resources.KeyEvent() + client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'key_event.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_key_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateKeyEventRequest() + + request.key_event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + await client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'key_event.name=name_value', + ) in kw['metadata'] + + +def test_update_key_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_key_event( + key_event=resources.KeyEvent(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].key_event + mock_val = resources.KeyEvent(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_key_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_event( + analytics_admin.UpdateKeyEventRequest(), + key_event=resources.KeyEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_key_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_key_event( + key_event=resources.KeyEvent(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].key_event + mock_val = resources.KeyEvent(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_key_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_event( + analytics_admin.UpdateKeyEventRequest(), + key_event=resources.KeyEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetKeyEventRequest, + dict, +]) +def test_get_key_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + response = client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +def test_get_key_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetKeyEventRequest() + + +def test_get_key_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetKeyEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_key_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetKeyEventRequest( + name='name_value', + ) + +def test_get_key_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_key_event] = mock_rpc + request = {} + client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_key_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.get_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetKeyEventRequest() + +@pytest.mark.asyncio +async def test_get_key_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_key_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_key_event] = mock_object + + request = {} + await client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_key_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetKeyEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_get_key_event_async_from_dict(): + await test_get_key_event_async(request_type=dict) + + +def test_get_key_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetKeyEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + call.return_value = resources.KeyEvent() + client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_key_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetKeyEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + await client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_key_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_key_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_key_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_event( + analytics_admin.GetKeyEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_key_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_key_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_key_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_event( + analytics_admin.GetKeyEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteKeyEventRequest, + dict, +]) +def test_delete_key_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_key_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteKeyEventRequest() + + +def test_delete_key_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteKeyEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_key_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteKeyEventRequest( + name='name_value', + ) + +def test_delete_key_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_key_event] = mock_rpc + request = {} + client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_key_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteKeyEventRequest() + +@pytest.mark.asyncio +async def test_delete_key_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_key_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_key_event] = mock_object + + request = {} + await client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_key_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteKeyEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteKeyEventRequest() + 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_key_event_async_from_dict(): + await test_delete_key_event_async(request_type=dict) + + +def test_delete_key_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteKeyEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__call__') as call: + call.return_value = None + client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_key_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteKeyEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_key_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__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_key_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_key_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_event( + analytics_admin.DeleteKeyEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_key_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__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_key_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_key_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_event( + analytics_admin.DeleteKeyEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListKeyEventsRequest, + dict, +]) +def test_list_key_events(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListKeyEventsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListKeyEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyEventsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_key_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_key_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListKeyEventsRequest() + + +def test_list_key_events_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListKeyEventsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_key_events(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListKeyEventsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_key_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_key_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_key_events] = mock_rpc + request = {} + client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_key_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_key_events_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListKeyEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_key_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListKeyEventsRequest() + +@pytest.mark.asyncio +async def test_list_key_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_key_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_key_events] = mock_object + + request = {} + await client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_key_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_key_events_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListKeyEventsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListKeyEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListKeyEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_key_events_async_from_dict(): + await test_list_key_events_async(request_type=dict) + + +def test_list_key_events_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListKeyEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + call.return_value = analytics_admin.ListKeyEventsResponse() + client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_key_events_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListKeyEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListKeyEventsResponse()) + await client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_key_events_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListKeyEventsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_key_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_key_events_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_events( + analytics_admin.ListKeyEventsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_key_events_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListKeyEventsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListKeyEventsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_key_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_key_events_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_events( + analytics_admin.ListKeyEventsRequest(), + parent='parent_value', + ) + + +def test_list_key_events_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_key_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_key_events(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.KeyEvent) + for i in results) +def test_list_key_events_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_key_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_key_events(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_key_events_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_key_events(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.KeyEvent) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_key_events_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + 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_key_events(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, + dict, +]) +def test_get_display_video360_advertiser_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + ) + response = client.get_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +def test_get_display_video360_advertiser_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_display_video360_advertiser_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + + +def test_get_display_video360_advertiser_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_display_video360_advertiser_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkRequest( + name='name_value', + ) + +def test_get_display_video360_advertiser_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_display_video360_advertiser_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_display_video360_advertiser_link] = mock_rpc + request = {} + client.get_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_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 = AnalyticsAdminServiceAsyncClient( + 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.get_display_video360_advertiser_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_display_video360_advertiser_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_display_video360_advertiser_link] = mock_object + + request = {} + await client.get_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.get_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_async_from_dict(): + await test_get_display_video360_advertiser_link_async(request_type=dict) + + +def test_get_display_video360_advertiser_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link), + '__call__') as call: + call.return_value = resources.DisplayVideo360AdvertiserLink() + client.get_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink()) + await client.get_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_display_video360_advertiser_link( + 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_display_video360_advertiser_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link( + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_display_video360_advertiser_link( + 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_display_video360_advertiser_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_display_video360_advertiser_link( + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, + dict, +]) +def test_list_display_video360_advertiser_links(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_display_video360_advertiser_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_display_video360_advertiser_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_display_video360_advertiser_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + + +def test_list_display_video360_advertiser_links_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_display_video360_advertiser_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_display_video360_advertiser_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_display_video360_advertiser_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_display_video360_advertiser_links] = mock_rpc + request = {} + client.list_display_video360_advertiser_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_display_video360_advertiser_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_links_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 = AnalyticsAdminServiceAsyncClient( + 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_display_video360_advertiser_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_display_video360_advertiser_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_display_video360_advertiser_links in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_display_video360_advertiser_links] = mock_object + + request = {} + await client.list_display_video360_advertiser_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_display_video360_advertiser_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_links_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_display_video360_advertiser_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_links_async_from_dict(): + await test_list_display_video360_advertiser_links_async(request_type=dict) + + +def test_list_display_video360_advertiser_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_links), + '__call__') as call: + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + client.list_display_video360_advertiser_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_links), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDisplayVideo360AdvertiserLinksResponse()) + await client.list_display_video360_advertiser_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_display_video360_advertiser_links( + 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_display_video360_advertiser_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_links( + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDisplayVideo360AdvertiserLinksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_display_video360_advertiser_links( + 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_display_video360_advertiser_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_display_video360_advertiser_links( + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(), + parent='parent_value', + ) + + +def test_list_display_video360_advertiser_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_display_video360_advertiser_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DisplayVideo360AdvertiserLink) + for i in results) +def test_list_display_video360_advertiser_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_display_video360_advertiser_links(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_display_video360_advertiser_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_display_video360_advertiser_links(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, resources.DisplayVideo360AdvertiserLink) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + ), + 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_display_video360_advertiser_links(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", [ + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, + dict, +]) +def test_create_display_video360_advertiser_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + ) + response = client.create_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +def test_create_display_video360_advertiser_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_display_video360_advertiser_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + + +def test_create_display_video360_advertiser_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_display_video360_advertiser_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest( + parent='parent_value', + ) + +def test_create_display_video360_advertiser_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_display_video360_advertiser_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_display_video360_advertiser_link] = mock_rpc + request = {} + client.create_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_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 = AnalyticsAdminServiceAsyncClient( + 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.create_display_video360_advertiser_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_display_video360_advertiser_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_display_video360_advertiser_link] = mock_object + + request = {} + await client.create_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.create_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_async_from_dict(): + await test_create_display_video360_advertiser_link_async(request_type=dict) + + +def test_create_display_video360_advertiser_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link), + '__call__') as call: + call.return_value = resources.DisplayVideo360AdvertiserLink() + client.create_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink()) + await client.create_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_display_video360_advertiser_link( + parent='parent_value', + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(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].display_video_360_advertiser_link + mock_val = resources.DisplayVideo360AdvertiserLink(name='name_value') + assert arg == mock_val + + +def test_create_display_video360_advertiser_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link( + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(), + parent='parent_value', + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_display_video360_advertiser_link( + parent='parent_value', + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(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].display_video_360_advertiser_link + mock_val = resources.DisplayVideo360AdvertiserLink(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_display_video360_advertiser_link( + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(), + parent='parent_value', + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, + dict, +]) +def test_delete_display_video360_advertiser_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_display_video360_advertiser_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_display_video360_advertiser_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + + +def test_delete_display_video360_advertiser_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_display_video360_advertiser_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest( + name='name_value', + ) + +def test_delete_display_video360_advertiser_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_display_video360_advertiser_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_display_video360_advertiser_link] = mock_rpc + request = {} + client.delete_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_display_video360_advertiser_link_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 = AnalyticsAdminServiceAsyncClient( + 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_display_video360_advertiser_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + +@pytest.mark.asyncio +async def test_delete_display_video360_advertiser_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_display_video360_advertiser_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_display_video360_advertiser_link] = mock_object + + request = {} + await client.delete_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_display_video360_advertiser_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + 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_display_video360_advertiser_link_async_from_dict(): + await test_delete_display_video360_advertiser_link_async(request_type=dict) + + +def test_delete_display_video360_advertiser_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link), + '__call__') as call: + call.return_value = None + client.delete_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link), + '__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_display_video360_advertiser_link( + 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_display_video360_advertiser_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_display_video360_advertiser_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link), + '__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_display_video360_advertiser_link( + 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_display_video360_advertiser_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_display_video360_advertiser_link( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, + dict, +]) +def test_update_display_video360_advertiser_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + ) + response = client.update_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +def test_update_display_video360_advertiser_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_display_video360_advertiser_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + + +def test_update_display_video360_advertiser_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_display_video360_advertiser_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_display_video360_advertiser_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest( + ) + +def test_update_display_video360_advertiser_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_display_video360_advertiser_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_display_video360_advertiser_link] = mock_rpc + request = {} + client.update_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_display_video360_advertiser_link_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 = AnalyticsAdminServiceAsyncClient( + 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.update_display_video360_advertiser_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + +@pytest.mark.asyncio +async def test_update_display_video360_advertiser_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_display_video360_advertiser_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_display_video360_advertiser_link] = mock_object + + request = {} + await client.update_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_display_video360_advertiser_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.update_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +@pytest.mark.asyncio +async def test_update_display_video360_advertiser_link_async_from_dict(): + await test_update_display_video360_advertiser_link_async(request_type=dict) + + +def test_update_display_video360_advertiser_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + + request.display_video_360_advertiser_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_display_video360_advertiser_link), + '__call__') as call: + call.return_value = resources.DisplayVideo360AdvertiserLink() + client.update_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'display_video_360_advertiser_link.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_display_video360_advertiser_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + + request.display_video_360_advertiser_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_display_video360_advertiser_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink()) + await client.update_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'display_video_360_advertiser_link.name=name_value', + ) in kw['metadata'] + + +def test_update_display_video360_advertiser_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_display_video360_advertiser_link( + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(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].display_video_360_advertiser_link + mock_val = resources.DisplayVideo360AdvertiserLink(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_display_video360_advertiser_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link( + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(), + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_display_video360_advertiser_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_display_video360_advertiser_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_display_video360_advertiser_link( + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(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].display_video_360_advertiser_link + mock_val = resources.DisplayVideo360AdvertiserLink(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_display_video360_advertiser_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_display_video360_advertiser_link( + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(), + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_get_display_video360_advertiser_link_proposal(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_value', + ) + response = client.get_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + assert response.validation_email == 'validation_email_value' + + +def test_get_display_video360_advertiser_link_proposal_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + + +def test_get_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_display_video360_advertiser_link_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest( + name='name_value', + ) + +def test_get_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_display_video360_advertiser_link_proposal] = mock_rpc + request = {} + client.get_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceAsyncClient( + 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_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_value', + )) + response = await client.get_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_display_video360_advertiser_link_proposal] = mock_object + + request = {} + await client.get_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_proposal_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_value', + )) + response = await client.get_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + assert response.validation_email == 'validation_email_value' + + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_proposal_async_from_dict(): + await test_get_display_video360_advertiser_link_proposal_async(request_type=dict) + + +def test_get_display_video360_advertiser_link_proposal_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + client.get_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_proposal_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal()) + await client.get_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_proposal_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_display_video360_advertiser_link_proposal( + 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_display_video360_advertiser_link_proposal_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link_proposal( + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_display_video360_advertiser_link_proposal_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_display_video360_advertiser_link_proposal( + 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_display_video360_advertiser_link_proposal_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_display_video360_advertiser_link_proposal( + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, + dict, +]) +def test_list_display_video360_advertiser_link_proposals(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link_proposals), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_display_video360_advertiser_link_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinkProposalsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_display_video360_advertiser_link_proposals_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link_proposals), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_display_video360_advertiser_link_proposals() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + + +def test_list_display_video360_advertiser_link_proposals_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_display_video360_advertiser_link_proposals(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_display_video360_advertiser_link_proposals_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_display_video360_advertiser_link_proposals in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_display_video360_advertiser_link_proposals] = mock_rpc + request = {} + client.list_display_video360_advertiser_link_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_display_video360_advertiser_link_proposals(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_link_proposals_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 = AnalyticsAdminServiceAsyncClient( + 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_display_video360_advertiser_link_proposals), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_display_video360_advertiser_link_proposals() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_link_proposals_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_display_video360_advertiser_link_proposals in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_display_video360_advertiser_link_proposals] = mock_object + + request = {} + await client.list_display_video360_advertiser_link_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_display_video360_advertiser_link_proposals(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_link_proposals_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link_proposals), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_display_video360_advertiser_link_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinkProposalsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_link_proposals_async_from_dict(): + await test_list_display_video360_advertiser_link_proposals_async(request_type=dict) + + +def test_list_display_video360_advertiser_link_proposals_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + '__call__') as call: + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + client.list_display_video360_advertiser_link_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_proposals_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse()) + await client.list_display_video360_advertiser_link_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_proposals_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_display_video360_advertiser_link_proposals( + 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_display_video360_advertiser_link_proposals_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link_proposals( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_link_proposals_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_display_video360_advertiser_link_proposals( + 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_display_video360_advertiser_link_proposals_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_display_video360_advertiser_link_proposals( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + parent='parent_value', + ) + + +def test_list_display_video360_advertiser_link_proposals_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link_proposals), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_display_video360_advertiser_link_proposals(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DisplayVideo360AdvertiserLinkProposal) + for i in results) +def test_list_display_video360_advertiser_link_proposals_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link_proposals), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + ), + RuntimeError, + ) + pages = list(client.list_display_video360_advertiser_link_proposals(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_display_video360_advertiser_link_proposals_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_display_video360_advertiser_link_proposals(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, resources.DisplayVideo360AdvertiserLinkProposal) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_display_video360_advertiser_link_proposals_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_display_video360_advertiser_link_proposals), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + ), + 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_display_video360_advertiser_link_proposals(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", [ + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_create_display_video360_advertiser_link_proposal(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_value', + ) + response = client.create_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + assert response.validation_email == 'validation_email_value' + + +def test_create_display_video360_advertiser_link_proposal_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + + +def test_create_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_display_video360_advertiser_link_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest( + parent='parent_value', + ) + +def test_create_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_display_video360_advertiser_link_proposal] = mock_rpc + request = {} + client.create_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceAsyncClient( + 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_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_value', + )) + response = await client.create_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_display_video360_advertiser_link_proposal] = mock_object + + request = {} + await client.create_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_proposal_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_value', + )) + response = await client.create_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + assert response.validation_email == 'validation_email_value' + + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_proposal_async_from_dict(): + await test_create_display_video360_advertiser_link_proposal_async(request_type=dict) + + +def test_create_display_video360_advertiser_link_proposal_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + client.create_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_proposal_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal()) + await client.create_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_proposal_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_display_video360_advertiser_link_proposal( + parent='parent_value', + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal(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].display_video_360_advertiser_link_proposal + mock_val = resources.DisplayVideo360AdvertiserLinkProposal(name='name_value') + assert arg == mock_val + + +def test_create_display_video360_advertiser_link_proposal_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link_proposal( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + parent='parent_value', + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_proposal_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_display_video360_advertiser_link_proposal( + parent='parent_value', + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal(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].display_video_360_advertiser_link_proposal + mock_val = resources.DisplayVideo360AdvertiserLinkProposal(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_display_video360_advertiser_link_proposal_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_display_video360_advertiser_link_proposal( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + parent='parent_value', + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_delete_display_video360_advertiser_link_proposal(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_display_video360_advertiser_link_proposal_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + + +def test_delete_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_display_video360_advertiser_link_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest( + name='name_value', + ) + +def test_delete_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_display_video360_advertiser_link_proposal] = mock_rpc + request = {} + client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceAsyncClient( + 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_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + +@pytest.mark.asyncio +async def test_delete_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_display_video360_advertiser_link_proposal] = mock_object + + request = {} + await client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_display_video360_advertiser_link_proposal_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + 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_display_video360_advertiser_link_proposal_async_from_dict(): + await test_delete_display_video360_advertiser_link_proposal_async(request_type=dict) + + +def test_delete_display_video360_advertiser_link_proposal_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = None + client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_proposal_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_display_video360_advertiser_link_proposal_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link_proposal), + '__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_display_video360_advertiser_link_proposal( + 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_display_video360_advertiser_link_proposal_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_display_video360_advertiser_link_proposal( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_display_video360_advertiser_link_proposal_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_display_video360_advertiser_link_proposal), + '__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_display_video360_advertiser_link_proposal( + 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_display_video360_advertiser_link_proposal_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_display_video360_advertiser_link_proposal( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_approve_display_video360_advertiser_link_proposal(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse( + ) + response = client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse) + + +def test_approve_display_video360_advertiser_link_proposal_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.approve_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + + +def test_approve_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.approve_display_video360_advertiser_link_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest( + name='name_value', + ) + +def test_approve_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.approve_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.approve_display_video360_advertiser_link_proposal] = mock_rpc + request = {} + client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_approve_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceAsyncClient( + 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.approve_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse( + )) + response = await client.approve_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + +@pytest.mark.asyncio +async def test_approve_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.approve_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.approve_display_video360_advertiser_link_proposal] = mock_object + + request = {} + await client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_approve_display_video360_advertiser_link_proposal_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse( + )) + response = await client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse) + + +@pytest.mark.asyncio +async def test_approve_display_video360_advertiser_link_proposal_async_from_dict(): + await test_approve_display_video360_advertiser_link_proposal_async(request_type=dict) + + +def test_approve_display_video360_advertiser_link_proposal_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_approve_display_video360_advertiser_link_proposal_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.approve_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse()) + await client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_cancel_display_video360_advertiser_link_proposal(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_value', + ) + response = client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + assert response.validation_email == 'validation_email_value' + + +def test_cancel_display_video360_advertiser_link_proposal_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.cancel_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + + +def test_cancel_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.cancel_display_video360_advertiser_link_proposal(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest( + name='name_value', + ) + +def test_cancel_display_video360_advertiser_link_proposal_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.cancel_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.cancel_display_video360_advertiser_link_proposal] = mock_rpc + request = {} + client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_cancel_display_video360_advertiser_link_proposal_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 = AnalyticsAdminServiceAsyncClient( + 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.cancel_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_value', + )) + response = await client.cancel_display_video360_advertiser_link_proposal() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + +@pytest.mark.asyncio +async def test_cancel_display_video360_advertiser_link_proposal_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.cancel_display_video360_advertiser_link_proposal in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.cancel_display_video360_advertiser_link_proposal] = mock_object + + request = {} + await client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_cancel_display_video360_advertiser_link_proposal_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_display_video360_advertiser_link_proposal), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_value', + )) + response = await client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + assert response.validation_email == 'validation_email_value' + + +@pytest.mark.asyncio +async def test_cancel_display_video360_advertiser_link_proposal_async_from_dict(): + await test_cancel_display_video360_advertiser_link_proposal_async(request_type=dict) + + +def test_cancel_display_video360_advertiser_link_proposal_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_cancel_display_video360_advertiser_link_proposal_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.cancel_display_video360_advertiser_link_proposal), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DisplayVideo360AdvertiserLinkProposal()) + await client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + analytics_admin.CreateCustomDimensionRequest, + dict, +]) +def test_create_custom_dimension(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + ) + response = client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +def test_create_custom_dimension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomDimensionRequest() + + +def test_create_custom_dimension_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateCustomDimensionRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_custom_dimension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomDimensionRequest( + parent='parent_value', + ) + +def test_create_custom_dimension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_custom_dimension] = mock_rpc + request = {} + client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_custom_dimension_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.create_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomDimensionRequest() + +@pytest.mark.asyncio +async def test_create_custom_dimension_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_custom_dimension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_custom_dimension] = mock_object + + request = {} + await client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_custom_dimension_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateCustomDimensionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +@pytest.mark.asyncio +async def test_create_custom_dimension_async_from_dict(): + await test_create_custom_dimension_async(request_type=dict) + + +def test_create_custom_dimension_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCustomDimensionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + call.return_value = resources.CustomDimension() + client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimension_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCustomDimensionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + await client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimension_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_custom_dimension( + parent='parent_value', + custom_dimension=resources.CustomDimension(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].custom_dimension + mock_val = resources.CustomDimension(name='name_value') + assert arg == mock_val + + +def test_create_custom_dimension_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension( + analytics_admin.CreateCustomDimensionRequest(), + parent='parent_value', + custom_dimension=resources.CustomDimension(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_custom_dimension_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_custom_dimension( + parent='parent_value', + custom_dimension=resources.CustomDimension(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].custom_dimension + mock_val = resources.CustomDimension(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_custom_dimension_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_dimension( + analytics_admin.CreateCustomDimensionRequest(), + parent='parent_value', + custom_dimension=resources.CustomDimension(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateCustomDimensionRequest, + dict, +]) +def test_update_custom_dimension(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + ) + response = client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +def test_update_custom_dimension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomDimensionRequest() + + +def test_update_custom_dimension_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateCustomDimensionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_custom_dimension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomDimensionRequest( + ) + +def test_update_custom_dimension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_custom_dimension] = mock_rpc + request = {} + client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_custom_dimension_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.update_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomDimensionRequest() + +@pytest.mark.asyncio +async def test_update_custom_dimension_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_custom_dimension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_custom_dimension] = mock_object + + request = {} + await client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_custom_dimension_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateCustomDimensionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +@pytest.mark.asyncio +async def test_update_custom_dimension_async_from_dict(): + await test_update_custom_dimension_async(request_type=dict) + + +def test_update_custom_dimension_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCustomDimensionRequest() + + request.custom_dimension.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + call.return_value = resources.CustomDimension() + client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'custom_dimension.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_custom_dimension_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCustomDimensionRequest() + + request.custom_dimension.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + await client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'custom_dimension.name=name_value', + ) in kw['metadata'] + + +def test_update_custom_dimension_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_custom_dimension( + custom_dimension=resources.CustomDimension(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].custom_dimension + mock_val = resources.CustomDimension(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_custom_dimension_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension( + analytics_admin.UpdateCustomDimensionRequest(), + custom_dimension=resources.CustomDimension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_custom_dimension_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_custom_dimension( + custom_dimension=resources.CustomDimension(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].custom_dimension + mock_val = resources.CustomDimension(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_custom_dimension_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_dimension( + analytics_admin.UpdateCustomDimensionRequest(), + custom_dimension=resources.CustomDimension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCustomDimensionsRequest, + dict, +]) +def test_list_custom_dimensions(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomDimensionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCustomDimensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomDimensionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_custom_dimensions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimensions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_custom_dimensions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomDimensionsRequest() + + +def test_list_custom_dimensions_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCustomDimensionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_custom_dimensions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomDimensionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_custom_dimensions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_custom_dimensions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_custom_dimensions] = mock_rpc + request = {} + client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_custom_dimensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_custom_dimensions_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomDimensionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_custom_dimensions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomDimensionsRequest() + +@pytest.mark.asyncio +async def test_list_custom_dimensions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_custom_dimensions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_custom_dimensions] = mock_object + + request = {} + await client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_custom_dimensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_custom_dimensions_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListCustomDimensionsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomDimensionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCustomDimensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomDimensionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_custom_dimensions_async_from_dict(): + await test_list_custom_dimensions_async(request_type=dict) + + +def test_list_custom_dimensions_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCustomDimensionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + call.return_value = analytics_admin.ListCustomDimensionsResponse() + client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimensions_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCustomDimensionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomDimensionsResponse()) + await client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimensions_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomDimensionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_custom_dimensions( + 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_custom_dimensions_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimensions( + analytics_admin.ListCustomDimensionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_custom_dimensions_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomDimensionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomDimensionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_custom_dimensions( + 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_custom_dimensions_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_dimensions( + analytics_admin.ListCustomDimensionsRequest(), + parent='parent_value', + ) + + +def test_list_custom_dimensions_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_custom_dimensions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_custom_dimensions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomDimension) + for i in results) +def test_list_custom_dimensions_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_custom_dimensions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + RuntimeError, + ) + pages = list(client.list_custom_dimensions(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_custom_dimensions_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_custom_dimensions(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, resources.CustomDimension) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_custom_dimensions_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + 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_custom_dimensions(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", [ + analytics_admin.ArchiveCustomDimensionRequest, + dict, +]) +def test_archive_custom_dimension(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_archive_custom_dimension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomDimensionRequest() + + +def test_archive_custom_dimension_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ArchiveCustomDimensionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_custom_dimension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomDimensionRequest( + name='name_value', + ) + +def test_archive_custom_dimension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_custom_dimension] = mock_rpc + request = {} + client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_custom_dimension_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 = AnalyticsAdminServiceAsyncClient( + 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.archive_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomDimensionRequest() + +@pytest.mark.asyncio +async def test_archive_custom_dimension_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.archive_custom_dimension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.archive_custom_dimension] = mock_object + + request = {} + await client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.archive_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_custom_dimension_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ArchiveCustomDimensionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_archive_custom_dimension_async_from_dict(): + await test_archive_custom_dimension_async(request_type=dict) + + +def test_archive_custom_dimension_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveCustomDimensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + call.return_value = None + client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_archive_custom_dimension_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveCustomDimensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_archive_custom_dimension_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__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.archive_custom_dimension( + 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_archive_custom_dimension_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.archive_custom_dimension( + analytics_admin.ArchiveCustomDimensionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_archive_custom_dimension_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__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.archive_custom_dimension( + 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_archive_custom_dimension_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.archive_custom_dimension( + analytics_admin.ArchiveCustomDimensionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCustomDimensionRequest, + dict, +]) +def test_get_custom_dimension(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + ) + response = client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +def test_get_custom_dimension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomDimensionRequest() + + +def test_get_custom_dimension_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetCustomDimensionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_custom_dimension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomDimensionRequest( + name='name_value', + ) + +def test_get_custom_dimension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_custom_dimension] = mock_rpc + request = {} + client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_custom_dimension_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.get_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomDimensionRequest() + +@pytest.mark.asyncio +async def test_get_custom_dimension_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_custom_dimension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_custom_dimension] = mock_object + + request = {} + await client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_custom_dimension_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetCustomDimensionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +@pytest.mark.asyncio +async def test_get_custom_dimension_async_from_dict(): + await test_get_custom_dimension_async(request_type=dict) + + +def test_get_custom_dimension_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCustomDimensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + call.return_value = resources.CustomDimension() + client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimension_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCustomDimensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + await client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimension_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_custom_dimension( + 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_custom_dimension_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension( + analytics_admin.GetCustomDimensionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_custom_dimension_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_custom_dimension( + 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_custom_dimension_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_dimension( + analytics_admin.GetCustomDimensionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateCustomMetricRequest, + dict, +]) +def test_create_custom_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + response = client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +def test_create_custom_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomMetricRequest() + + +def test_create_custom_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateCustomMetricRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_custom_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomMetricRequest( + parent='parent_value', + ) + +def test_create_custom_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_custom_metric] = mock_rpc + request = {} + client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_custom_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.create_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomMetricRequest() + +@pytest.mark.asyncio +async def test_create_custom_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_custom_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_custom_metric] = mock_object + + request = {} + await client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_custom_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateCustomMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +@pytest.mark.asyncio +async def test_create_custom_metric_async_from_dict(): + await test_create_custom_metric_async(request_type=dict) + + +def test_create_custom_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCustomMetricRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + call.return_value = resources.CustomMetric() + client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCustomMetricRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + await client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_custom_metric( + parent='parent_value', + custom_metric=resources.CustomMetric(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].custom_metric + mock_val = resources.CustomMetric(name='name_value') + assert arg == mock_val + + +def test_create_custom_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric( + analytics_admin.CreateCustomMetricRequest(), + parent='parent_value', + custom_metric=resources.CustomMetric(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_custom_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_custom_metric( + parent='parent_value', + custom_metric=resources.CustomMetric(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].custom_metric + mock_val = resources.CustomMetric(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_custom_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_metric( + analytics_admin.CreateCustomMetricRequest(), + parent='parent_value', + custom_metric=resources.CustomMetric(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateCustomMetricRequest, + dict, +]) +def test_update_custom_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + response = client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +def test_update_custom_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomMetricRequest() + + +def test_update_custom_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateCustomMetricRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_custom_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomMetricRequest( + ) + +def test_update_custom_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_custom_metric] = mock_rpc + request = {} + client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_custom_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.update_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomMetricRequest() + +@pytest.mark.asyncio +async def test_update_custom_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_custom_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_custom_metric] = mock_object + + request = {} + await client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_custom_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateCustomMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +@pytest.mark.asyncio +async def test_update_custom_metric_async_from_dict(): + await test_update_custom_metric_async(request_type=dict) + + +def test_update_custom_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCustomMetricRequest() + + request.custom_metric.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + call.return_value = resources.CustomMetric() + client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'custom_metric.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_custom_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCustomMetricRequest() + + request.custom_metric.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + await client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'custom_metric.name=name_value', + ) in kw['metadata'] + + +def test_update_custom_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_custom_metric( + custom_metric=resources.CustomMetric(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].custom_metric + mock_val = resources.CustomMetric(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_custom_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric( + analytics_admin.UpdateCustomMetricRequest(), + custom_metric=resources.CustomMetric(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_custom_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_custom_metric( + custom_metric=resources.CustomMetric(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].custom_metric + mock_val = resources.CustomMetric(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_custom_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_metric( + analytics_admin.UpdateCustomMetricRequest(), + custom_metric=resources.CustomMetric(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCustomMetricsRequest, + dict, +]) +def test_list_custom_metrics(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomMetricsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCustomMetricsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomMetricsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_custom_metrics_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_metrics), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_custom_metrics() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomMetricsRequest() + + +def test_list_custom_metrics_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCustomMetricsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_custom_metrics(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomMetricsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_custom_metrics_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_custom_metrics in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_custom_metrics] = mock_rpc + request = {} + client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_custom_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_custom_metrics_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomMetricsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_custom_metrics() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomMetricsRequest() + +@pytest.mark.asyncio +async def test_list_custom_metrics_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_custom_metrics in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_custom_metrics] = mock_object + + request = {} + await client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_custom_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_custom_metrics_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListCustomMetricsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomMetricsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCustomMetricsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomMetricsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_custom_metrics_async_from_dict(): + await test_list_custom_metrics_async(request_type=dict) + + +def test_list_custom_metrics_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCustomMetricsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + call.return_value = analytics_admin.ListCustomMetricsResponse() + client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metrics_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCustomMetricsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomMetricsResponse()) + await client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metrics_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomMetricsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_custom_metrics( + 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_custom_metrics_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_metrics( + analytics_admin.ListCustomMetricsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_custom_metrics_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomMetricsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomMetricsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_custom_metrics( + 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_custom_metrics_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_metrics( + analytics_admin.ListCustomMetricsRequest(), + parent='parent_value', + ) + + +def test_list_custom_metrics_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_custom_metrics), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_custom_metrics(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomMetric) + for i in results) +def test_list_custom_metrics_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_custom_metrics), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, + ) + pages = list(client.list_custom_metrics(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_custom_metrics_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_custom_metrics(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, resources.CustomMetric) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_custom_metrics_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + 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_custom_metrics(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", [ + analytics_admin.ArchiveCustomMetricRequest, + dict, +]) +def test_archive_custom_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_archive_custom_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomMetricRequest() + + +def test_archive_custom_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ArchiveCustomMetricRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_custom_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomMetricRequest( + name='name_value', + ) + +def test_archive_custom_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_custom_metric] = mock_rpc + request = {} + client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_custom_metric_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 = AnalyticsAdminServiceAsyncClient( + 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.archive_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomMetricRequest() + +@pytest.mark.asyncio +async def test_archive_custom_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.archive_custom_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.archive_custom_metric] = mock_object + + request = {} + await client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.archive_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_custom_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ArchiveCustomMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_archive_custom_metric_async_from_dict(): + await test_archive_custom_metric_async(request_type=dict) + + +def test_archive_custom_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveCustomMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + call.return_value = None + client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_archive_custom_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveCustomMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_archive_custom_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__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.archive_custom_metric( + 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_archive_custom_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.archive_custom_metric( + analytics_admin.ArchiveCustomMetricRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_archive_custom_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__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.archive_custom_metric( + 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_archive_custom_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.archive_custom_metric( + analytics_admin.ArchiveCustomMetricRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCustomMetricRequest, + dict, +]) +def test_get_custom_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + response = client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +def test_get_custom_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomMetricRequest() + + +def test_get_custom_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetCustomMetricRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_custom_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomMetricRequest( + name='name_value', + ) + +def test_get_custom_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_custom_metric] = mock_rpc + request = {} + client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_custom_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.get_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomMetricRequest() + +@pytest.mark.asyncio +async def test_get_custom_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_custom_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_custom_metric] = mock_object + + request = {} + await client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_custom_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetCustomMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +@pytest.mark.asyncio +async def test_get_custom_metric_async_from_dict(): + await test_get_custom_metric_async(request_type=dict) + + +def test_get_custom_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCustomMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + call.return_value = resources.CustomMetric() + client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCustomMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + await client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_custom_metric( + 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_custom_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric( + analytics_admin.GetCustomMetricRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_custom_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_custom_metric( + 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_custom_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_metric( + analytics_admin.GetCustomMetricRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataRetentionSettingsRequest, + dict, +]) +def test_get_data_retention_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + ) + response = client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataRetentionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + + +def test_get_data_retention_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_retention_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataRetentionSettingsRequest() + + +def test_get_data_retention_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetDataRetentionSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_retention_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataRetentionSettingsRequest( + name='name_value', + ) + +def test_get_data_retention_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_retention_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_retention_settings] = mock_rpc + request = {} + client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_retention_settings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + )) + response = await client.get_data_retention_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataRetentionSettingsRequest() + +@pytest.mark.asyncio +async def test_get_data_retention_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_data_retention_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_data_retention_settings] = mock_object + + request = {} + await client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_retention_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetDataRetentionSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + )) + response = await client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataRetentionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + + +@pytest.mark.asyncio +async def test_get_data_retention_settings_async_from_dict(): + await test_get_data_retention_settings_async(request_type=dict) + + +def test_get_data_retention_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataRetentionSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + call.return_value = resources.DataRetentionSettings() + client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_data_retention_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataRetentionSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings()) + await client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_data_retention_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_retention_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_data_retention_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_retention_settings( + analytics_admin.GetDataRetentionSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_retention_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_retention_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_data_retention_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_retention_settings( + analytics_admin.GetDataRetentionSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDataRetentionSettingsRequest, + dict, +]) +def test_update_data_retention_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + ) + response = client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataRetentionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + + +def test_update_data_retention_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_retention_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() + + +def test_update_data_retention_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateDataRetentionSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_retention_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest( + ) + +def test_update_data_retention_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_retention_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_retention_settings] = mock_rpc + request = {} + client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_retention_settings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + )) + response = await client.update_data_retention_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() + +@pytest.mark.asyncio +async def test_update_data_retention_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_data_retention_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_data_retention_settings] = mock_object + + request = {} + await client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_retention_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateDataRetentionSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + )) + response = await client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataRetentionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + + +@pytest.mark.asyncio +async def test_update_data_retention_settings_async_from_dict(): + await test_update_data_retention_settings_async(request_type=dict) + + +def test_update_data_retention_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataRetentionSettingsRequest() + + request.data_retention_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + call.return_value = resources.DataRetentionSettings() + client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_retention_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_data_retention_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataRetentionSettingsRequest() + + request.data_retention_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings()) + await client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_retention_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_data_retention_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_retention_settings( + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].data_retention_settings + mock_val = resources.DataRetentionSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_data_retention_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_retention_settings( + analytics_admin.UpdateDataRetentionSettingsRequest(), + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_data_retention_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_retention_settings( + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].data_retention_settings + mock_val = resources.DataRetentionSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_data_retention_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_data_retention_settings( + analytics_admin.UpdateDataRetentionSettingsRequest(), + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateDataStreamRequest, + dict, +]) +def test_create_data_stream(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + ) + response = client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +def test_create_data_stream_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDataStreamRequest() + + +def test_create_data_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateDataStreamRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_data_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDataStreamRequest( + parent='parent_value', + ) + +def test_create_data_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_data_stream] = mock_rpc + request = {} + client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_data_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.create_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDataStreamRequest() + +@pytest.mark.asyncio +async def test_create_data_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_data_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_data_stream] = mock_object + + request = {} + await client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_data_stream_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateDataStreamRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_create_data_stream_async_from_dict(): + await test_create_data_stream_async(request_type=dict) + + +def test_create_data_stream_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateDataStreamRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + call.return_value = resources.DataStream() + client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_data_stream_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateDataStreamRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + await client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_data_stream_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_data_stream( + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_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].data_stream + mock_val = resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')) + assert arg == mock_val + + +def test_create_data_stream_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_data_stream( + analytics_admin.CreateDataStreamRequest(), + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + ) + +@pytest.mark.asyncio +async def test_create_data_stream_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_data_stream( + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_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].data_stream + mock_val = resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_data_stream_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_data_stream( + analytics_admin.CreateDataStreamRequest(), + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteDataStreamRequest, + dict, +]) +def test_delete_data_stream(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_data_stream_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDataStreamRequest() + + +def test_delete_data_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteDataStreamRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_data_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDataStreamRequest( + name='name_value', + ) + +def test_delete_data_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_data_stream] = mock_rpc + request = {} + client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_data_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDataStreamRequest() + +@pytest.mark.asyncio +async def test_delete_data_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_data_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_data_stream] = mock_object + + request = {} + await client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_data_stream_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteDataStreamRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_data_stream_async_from_dict(): + await test_delete_data_stream_async(request_type=dict) + + +def test_delete_data_stream_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteDataStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + call.return_value = None + client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_data_stream_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteDataStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_data_stream_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_data_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_data_stream_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_data_stream( + analytics_admin.DeleteDataStreamRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_data_stream_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_data_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_data_stream_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_data_stream( + analytics_admin.DeleteDataStreamRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDataStreamRequest, + dict, +]) +def test_update_data_stream(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + ) + response = client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +def test_update_data_stream_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataStreamRequest() + + +def test_update_data_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateDataStreamRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataStreamRequest( + ) + +def test_update_data_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_stream] = mock_rpc + request = {} + client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.update_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataStreamRequest() + +@pytest.mark.asyncio +async def test_update_data_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_data_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_data_stream] = mock_object + + request = {} + await client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_stream_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateDataStreamRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_data_stream_async_from_dict(): + await test_update_data_stream_async(request_type=dict) + + +def test_update_data_stream_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataStreamRequest() + + request.data_stream.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + call.return_value = resources.DataStream() + client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_stream.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_data_stream_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataStreamRequest() + + request.data_stream.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + await client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_stream.name=name_value', + ) in kw['metadata'] + + +def test_update_data_stream_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_stream( + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].data_stream + mock_val = resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_data_stream_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_stream( + analytics_admin.UpdateDataStreamRequest(), + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_data_stream_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_stream( + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].data_stream + mock_val = resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_data_stream_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_data_stream( + analytics_admin.UpdateDataStreamRequest(), + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListDataStreamsRequest, + dict, +]) +def test_list_data_streams(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDataStreamsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListDataStreamsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataStreamsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_data_streams_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_data_streams() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDataStreamsRequest() + + +def test_list_data_streams_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListDataStreamsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_data_streams(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDataStreamsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_data_streams_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_streams in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_data_streams] = mock_rpc + request = {} + client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_data_streams_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDataStreamsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_streams() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDataStreamsRequest() + +@pytest.mark.asyncio +async def test_list_data_streams_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_data_streams in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_data_streams] = mock_object + + request = {} + await client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_data_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_data_streams_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListDataStreamsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDataStreamsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListDataStreamsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataStreamsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_data_streams_async_from_dict(): + await test_list_data_streams_async(request_type=dict) + + +def test_list_data_streams_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListDataStreamsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + call.return_value = analytics_admin.ListDataStreamsResponse() + client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_data_streams_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListDataStreamsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDataStreamsResponse()) + await client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_data_streams_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDataStreamsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_streams( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_data_streams_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_streams( + analytics_admin.ListDataStreamsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_data_streams_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDataStreamsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDataStreamsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_streams( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_data_streams_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_data_streams( + analytics_admin.ListDataStreamsRequest(), + parent='parent_value', + ) + + +def test_list_data_streams_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_data_streams(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DataStream) + for i in results) +def test_list_data_streams_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_streams(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_data_streams_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_streams(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.DataStream) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_data_streams_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_data_streams(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataStreamRequest, + dict, +]) +def test_get_data_stream(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + ) + response = client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +def test_get_data_stream_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataStreamRequest() + + +def test_get_data_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetDataStreamRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataStreamRequest( + name='name_value', + ) + +def test_get_data_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_stream] = mock_rpc + request = {} + client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.get_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataStreamRequest() + +@pytest.mark.asyncio +async def test_get_data_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_data_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_data_stream] = mock_object + + request = {} + await client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_stream_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetDataStreamRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_data_stream_async_from_dict(): + await test_get_data_stream_async(request_type=dict) + + +def test_get_data_stream_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + call.return_value = resources.DataStream() + client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_data_stream_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + await client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_data_stream_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_data_stream_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_stream( + analytics_admin.GetDataStreamRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_stream_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_data_stream_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_stream( + analytics_admin.GetDataStreamRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAudienceRequest, + dict, +]) +def test_get_audience(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + response = client.get_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAudienceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, audience.Audience) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert response.exclusion_duration_mode == audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + + +def test_get_audience_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_audience), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_audience() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAudienceRequest() + + +def test_get_audience_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetAudienceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_audience), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_audience(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAudienceRequest( + name='name_value', + ) + +def test_get_audience_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_audience in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_audience] = mock_rpc + request = {} + client.get_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_audience_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 = AnalyticsAdminServiceAsyncClient( + 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_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + )) + response = await client.get_audience() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAudienceRequest() + +@pytest.mark.asyncio +async def test_get_audience_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_audience in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_audience] = mock_object + + request = {} + await client.get_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_audience_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetAudienceRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + )) + response = await client.get_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAudienceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, audience.Audience) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert response.exclusion_duration_mode == audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + + +@pytest.mark.asyncio +async def test_get_audience_async_from_dict(): + await test_get_audience_async(request_type=dict) + + +def test_get_audience_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAudienceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_audience), + '__call__') as call: + call.return_value = audience.Audience() + client.get_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_audience_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAudienceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_audience), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(audience.Audience()) + await client.get_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_audience_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = audience.Audience() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_audience( + 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_audience_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_audience( + analytics_admin.GetAudienceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_audience_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = audience.Audience() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(audience.Audience()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_audience( + 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_audience_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_audience( + analytics_admin.GetAudienceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAudiencesRequest, + dict, +]) +def test_list_audiences(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_audiences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAudiencesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_audiences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAudiencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAudiencesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_audiences_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_audiences), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_audiences() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAudiencesRequest() + + +def test_list_audiences_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAudiencesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_audiences), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_audiences(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAudiencesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_audiences_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_audiences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_audiences] = mock_rpc + request = {} + client.list_audiences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_audiences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_audiences_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 = AnalyticsAdminServiceAsyncClient( + 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_audiences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAudiencesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_audiences() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAudiencesRequest() + +@pytest.mark.asyncio +async def test_list_audiences_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_audiences in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_audiences] = mock_object + + request = {} + await client.list_audiences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_audiences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_audiences_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListAudiencesRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_audiences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAudiencesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_audiences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAudiencesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAudiencesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_audiences_async_from_dict(): + await test_list_audiences_async(request_type=dict) + + +def test_list_audiences_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListAudiencesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_audiences), + '__call__') as call: + call.return_value = analytics_admin.ListAudiencesResponse() + client.list_audiences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_audiences_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListAudiencesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_audiences), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAudiencesResponse()) + await client.list_audiences(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_audiences_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_audiences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAudiencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_audiences( + 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_audiences_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_audiences( + analytics_admin.ListAudiencesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_audiences_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_audiences), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAudiencesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAudiencesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_audiences( + 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_audiences_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_audiences( + analytics_admin.ListAudiencesRequest(), + parent='parent_value', + ) + + +def test_list_audiences_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_audiences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), + ], + next_page_token='abc', + ), + analytics_admin.ListAudiencesResponse( + audiences=[], + next_page_token='def', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_audiences(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, audience.Audience) + for i in results) +def test_list_audiences_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_audiences), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), + ], + next_page_token='abc', + ), + analytics_admin.ListAudiencesResponse( + audiences=[], + next_page_token='def', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + ], + ), + RuntimeError, + ) + pages = list(client.list_audiences(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_audiences_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_audiences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), + ], + next_page_token='abc', + ), + analytics_admin.ListAudiencesResponse( + audiences=[], + next_page_token='def', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_audiences(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, audience.Audience) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_audiences_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_audiences), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), + ], + next_page_token='abc', + ), + analytics_admin.ListAudiencesResponse( + audiences=[], + next_page_token='def', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + ], + ), + 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_audiences(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", [ + analytics_admin.CreateAudienceRequest, + dict, +]) +def test_create_audience(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + response = client.create_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateAudienceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_audience.Audience) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert response.exclusion_duration_mode == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + + +def test_create_audience_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_audience), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_audience() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateAudienceRequest() + + +def test_create_audience_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateAudienceRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_audience), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_audience(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateAudienceRequest( + parent='parent_value', + ) + +def test_create_audience_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_audience in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_audience] = mock_rpc + request = {} + client.create_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_audience_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 = AnalyticsAdminServiceAsyncClient( + 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_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + )) + response = await client.create_audience() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateAudienceRequest() + +@pytest.mark.asyncio +async def test_create_audience_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_audience in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_audience] = mock_object + + request = {} + await client.create_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_audience_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateAudienceRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gaa_audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + )) + response = await client.create_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateAudienceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_audience.Audience) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert response.exclusion_duration_mode == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + + +@pytest.mark.asyncio +async def test_create_audience_async_from_dict(): + await test_create_audience_async(request_type=dict) + + +def test_create_audience_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateAudienceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_audience), + '__call__') as call: + call.return_value = gaa_audience.Audience() + client.create_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_audience_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateAudienceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_audience), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_audience.Audience()) + await client.create_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_audience_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_audience.Audience() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_audience( + parent='parent_value', + audience=gaa_audience.Audience(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].audience + mock_val = gaa_audience.Audience(name='name_value') + assert arg == mock_val + + +def test_create_audience_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_audience( + analytics_admin.CreateAudienceRequest(), + parent='parent_value', + audience=gaa_audience.Audience(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_audience_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_audience.Audience() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_audience.Audience()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_audience( + parent='parent_value', + audience=gaa_audience.Audience(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].audience + mock_val = gaa_audience.Audience(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_audience_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_audience( + analytics_admin.CreateAudienceRequest(), + parent='parent_value', + audience=gaa_audience.Audience(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAudienceRequest, + dict, +]) +def test_update_audience(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + response = client.update_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAudienceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_audience.Audience) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert response.exclusion_duration_mode == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + + +def test_update_audience_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_audience), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_audience() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAudienceRequest() + + +def test_update_audience_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateAudienceRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_audience), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_audience(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAudienceRequest( + ) + +def test_update_audience_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_audience in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_audience] = mock_rpc + request = {} + client.update_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_audience_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 = AnalyticsAdminServiceAsyncClient( + 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_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + )) + response = await client.update_audience() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAudienceRequest() + +@pytest.mark.asyncio +async def test_update_audience_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_audience in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_audience] = mock_object + + request = {} + await client.update_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_audience_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateAudienceRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gaa_audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + )) + response = await client.update_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAudienceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_audience.Audience) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert response.exclusion_duration_mode == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + + +@pytest.mark.asyncio +async def test_update_audience_async_from_dict(): + await test_update_audience_async(request_type=dict) + + +def test_update_audience_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAudienceRequest() + + request.audience.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_audience), + '__call__') as call: + call.return_value = gaa_audience.Audience() + client.update_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'audience.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_audience_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAudienceRequest() + + request.audience.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_audience), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_audience.Audience()) + await client.update_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'audience.name=name_value', + ) in kw['metadata'] + + +def test_update_audience_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_audience.Audience() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_audience( + audience=gaa_audience.Audience(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].audience + mock_val = gaa_audience.Audience(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_audience_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_audience( + analytics_admin.UpdateAudienceRequest(), + audience=gaa_audience.Audience(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_audience_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_audience.Audience() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_audience.Audience()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_audience( + audience=gaa_audience.Audience(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].audience + mock_val = gaa_audience.Audience(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_audience_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_audience( + analytics_admin.UpdateAudienceRequest(), + audience=gaa_audience.Audience(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ArchiveAudienceRequest, + dict, +]) +def test_archive_audience(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.archive_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveAudienceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_archive_audience_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_audience), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_audience() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveAudienceRequest() + + +def test_archive_audience_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ArchiveAudienceRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_audience), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_audience(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveAudienceRequest( + name='name_value', + ) + +def test_archive_audience_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_audience in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_audience] = mock_rpc + request = {} + client.archive_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_audience_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 = AnalyticsAdminServiceAsyncClient( + 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.archive_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_audience() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveAudienceRequest() + +@pytest.mark.asyncio +async def test_archive_audience_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.archive_audience in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.archive_audience] = mock_object + + request = {} + await client.archive_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.archive_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_audience_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ArchiveAudienceRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_audience), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveAudienceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_archive_audience_async_from_dict(): + await test_archive_audience_async(request_type=dict) + + +def test_archive_audience_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveAudienceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_audience), + '__call__') as call: + call.return_value = None + client.archive_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_archive_audience_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveAudienceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_audience), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.archive_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + analytics_admin.GetSearchAds360LinkRequest, + dict, +]) +def test_get_search_ads360_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + ) + response = client.get_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetSearchAds360LinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SearchAds360Link) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +def test_get_search_ads360_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_ads360_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_search_ads360_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSearchAds360LinkRequest() + + +def test_get_search_ads360_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetSearchAds360LinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_ads360_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_search_ads360_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSearchAds360LinkRequest( + name='name_value', + ) + +def test_get_search_ads360_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_search_ads360_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_search_ads360_link] = mock_rpc + request = {} + client.get_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_search_ads360_link_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.get_search_ads360_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSearchAds360LinkRequest() + +@pytest.mark.asyncio +async def test_get_search_ads360_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_search_ads360_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_search_ads360_link] = mock_object + + request = {} + await client.get_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_search_ads360_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetSearchAds360LinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.get_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetSearchAds360LinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SearchAds360Link) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +@pytest.mark.asyncio +async def test_get_search_ads360_link_async_from_dict(): + await test_get_search_ads360_link_async(request_type=dict) + + +def test_get_search_ads360_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetSearchAds360LinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_ads360_link), + '__call__') as call: + call.return_value = resources.SearchAds360Link() + client.get_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_search_ads360_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetSearchAds360LinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_ads360_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link()) + await client.get_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_search_ads360_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_search_ads360_link( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_search_ads360_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_search_ads360_link( + analytics_admin.GetSearchAds360LinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_search_ads360_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_search_ads360_link( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_search_ads360_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_search_ads360_link( + analytics_admin.GetSearchAds360LinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListSearchAds360LinksRequest, + dict, +]) +def test_list_search_ads360_links(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSearchAds360LinksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_search_ads360_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListSearchAds360LinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchAds360LinksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_search_ads360_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_search_ads360_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSearchAds360LinksRequest() + + +def test_list_search_ads360_links_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListSearchAds360LinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_search_ads360_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSearchAds360LinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_search_ads360_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_search_ads360_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_search_ads360_links] = mock_rpc + request = {} + client.list_search_ads360_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_search_ads360_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_search_ads360_links_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSearchAds360LinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_search_ads360_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSearchAds360LinksRequest() + +@pytest.mark.asyncio +async def test_list_search_ads360_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_search_ads360_links in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_search_ads360_links] = mock_object + + request = {} + await client.list_search_ads360_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_search_ads360_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_search_ads360_links_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListSearchAds360LinksRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSearchAds360LinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_search_ads360_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListSearchAds360LinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchAds360LinksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_search_ads360_links_async_from_dict(): + await test_list_search_ads360_links_async(request_type=dict) + + +def test_list_search_ads360_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListSearchAds360LinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + call.return_value = analytics_admin.ListSearchAds360LinksResponse() + client.list_search_ads360_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_search_ads360_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListSearchAds360LinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSearchAds360LinksResponse()) + await client.list_search_ads360_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_search_ads360_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSearchAds360LinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_search_ads360_links( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_search_ads360_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_search_ads360_links( + analytics_admin.ListSearchAds360LinksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_search_ads360_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSearchAds360LinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSearchAds360LinksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_search_ads360_links( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_search_ads360_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_search_ads360_links( + analytics_admin.ListSearchAds360LinksRequest(), + parent='parent_value', + ) + + +def test_list_search_ads360_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token='abc', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token='def', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_search_ads360_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SearchAds360Link) + for i in results) +def test_list_search_ads360_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token='abc', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token='def', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + RuntimeError, + ) + pages = list(client.list_search_ads360_links(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_search_ads360_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token='abc', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token='def', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_search_ads360_links(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, resources.SearchAds360Link) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_search_ads360_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_search_ads360_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token='abc', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token='def', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_search_ads360_links(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", [ + analytics_admin.CreateSearchAds360LinkRequest, + dict, +]) +def test_create_search_ads360_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + ) + response = client.create_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateSearchAds360LinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SearchAds360Link) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +def test_create_search_ads360_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_search_ads360_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSearchAds360LinkRequest() + + +def test_create_search_ads360_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateSearchAds360LinkRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_search_ads360_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSearchAds360LinkRequest( + parent='parent_value', + ) + +def test_create_search_ads360_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_search_ads360_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_search_ads360_link] = mock_rpc + request = {} + client.create_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_search_ads360_link_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.create_search_ads360_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSearchAds360LinkRequest() + +@pytest.mark.asyncio +async def test_create_search_ads360_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_search_ads360_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_search_ads360_link] = mock_object + + request = {} + await client.create_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_search_ads360_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateSearchAds360LinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.create_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateSearchAds360LinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SearchAds360Link) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +@pytest.mark.asyncio +async def test_create_search_ads360_link_async_from_dict(): + await test_create_search_ads360_link_async(request_type=dict) + + +def test_create_search_ads360_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateSearchAds360LinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), + '__call__') as call: + call.return_value = resources.SearchAds360Link() + client.create_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_search_ads360_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateSearchAds360LinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link()) + await client.create_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_search_ads360_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_search_ads360_link( + parent='parent_value', + search_ads_360_link=resources.SearchAds360Link(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].search_ads_360_link + mock_val = resources.SearchAds360Link(name='name_value') + assert arg == mock_val + + +def test_create_search_ads360_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_search_ads360_link( + analytics_admin.CreateSearchAds360LinkRequest(), + parent='parent_value', + search_ads_360_link=resources.SearchAds360Link(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_search_ads360_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_search_ads360_link( + parent='parent_value', + search_ads_360_link=resources.SearchAds360Link(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].search_ads_360_link + mock_val = resources.SearchAds360Link(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_search_ads360_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_search_ads360_link( + analytics_admin.CreateSearchAds360LinkRequest(), + parent='parent_value', + search_ads_360_link=resources.SearchAds360Link(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteSearchAds360LinkRequest, + dict, +]) +def test_delete_search_ads360_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteSearchAds360LinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_search_ads360_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_ads360_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_search_ads360_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSearchAds360LinkRequest() + + +def test_delete_search_ads360_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteSearchAds360LinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_ads360_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_search_ads360_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSearchAds360LinkRequest( + name='name_value', + ) + +def test_delete_search_ads360_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_search_ads360_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_search_ads360_link] = mock_rpc + request = {} + client.delete_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_search_ads360_link_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_ads360_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSearchAds360LinkRequest() + +@pytest.mark.asyncio +async def test_delete_search_ads360_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_search_ads360_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_search_ads360_link] = mock_object + + request = {} + await client.delete_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_search_ads360_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteSearchAds360LinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteSearchAds360LinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_search_ads360_link_async_from_dict(): + await test_delete_search_ads360_link_async(request_type=dict) + + +def test_delete_search_ads360_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteSearchAds360LinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_ads360_link), + '__call__') as call: + call.return_value = None + client.delete_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_search_ads360_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteSearchAds360LinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_ads360_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_search_ads360_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_search_ads360_link( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_search_ads360_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_search_ads360_link( + analytics_admin.DeleteSearchAds360LinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_search_ads360_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_search_ads360_link( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_search_ads360_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_search_ads360_link( + analytics_admin.DeleteSearchAds360LinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateSearchAds360LinkRequest, + dict, +]) +def test_update_search_ads360_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + ) + response = client.update_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateSearchAds360LinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SearchAds360Link) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +def test_update_search_ads360_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_ads360_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_search_ads360_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSearchAds360LinkRequest() + + +def test_update_search_ads360_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateSearchAds360LinkRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_ads360_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_search_ads360_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSearchAds360LinkRequest( + ) + +def test_update_search_ads360_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_search_ads360_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_search_ads360_link] = mock_rpc + request = {} + client.update_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_search_ads360_link_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.update_search_ads360_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSearchAds360LinkRequest() + +@pytest.mark.asyncio +async def test_update_search_ads360_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_search_ads360_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_search_ads360_link] = mock_object + + request = {} + await client.update_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_search_ads360_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateSearchAds360LinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + )) + response = await client.update_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateSearchAds360LinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SearchAds360Link) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + + +@pytest.mark.asyncio +async def test_update_search_ads360_link_async_from_dict(): + await test_update_search_ads360_link_async(request_type=dict) + + +def test_update_search_ads360_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateSearchAds360LinkRequest() + + request.search_ads_360_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_ads360_link), + '__call__') as call: + call.return_value = resources.SearchAds360Link() + client.update_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'search_ads_360_link.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_search_ads360_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateSearchAds360LinkRequest() + + request.search_ads_360_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_ads360_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link()) + await client.update_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'search_ads_360_link.name=name_value', + ) in kw['metadata'] + + +def test_update_search_ads360_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_search_ads360_link( + search_ads_360_link=resources.SearchAds360Link(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].search_ads_360_link + mock_val = resources.SearchAds360Link(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_search_ads360_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_search_ads360_link( + analytics_admin.UpdateSearchAds360LinkRequest(), + search_ads_360_link=resources.SearchAds360Link(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_search_ads360_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_search_ads360_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SearchAds360Link() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.SearchAds360Link()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_search_ads360_link( + search_ads_360_link=resources.SearchAds360Link(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].search_ads_360_link + mock_val = resources.SearchAds360Link(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_search_ads360_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_search_ads360_link( + analytics_admin.UpdateSearchAds360LinkRequest(), + search_ads_360_link=resources.SearchAds360Link(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAttributionSettingsRequest, + dict, +]) +def test_get_attribution_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AttributionSettings( + name='name_value', + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + ) + response = client.get_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAttributionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AttributionSettings) + assert response.name == 'name_value' + assert response.acquisition_conversion_event_lookback_window == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + assert response.other_conversion_event_lookback_window == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + assert response.reporting_attribution_model == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + assert response.ads_web_conversion_data_export_scope == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + + +def test_get_attribution_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_attribution_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_attribution_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAttributionSettingsRequest() + + +def test_get_attribution_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetAttributionSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attribution_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_attribution_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAttributionSettingsRequest( + name='name_value', + ) + +def test_get_attribution_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_attribution_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_attribution_settings] = mock_rpc + request = {} + client.get_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_attribution_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_attribution_settings_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 = AnalyticsAdminServiceAsyncClient( + 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_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AttributionSettings( + name='name_value', + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + )) + response = await client.get_attribution_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAttributionSettingsRequest() + +@pytest.mark.asyncio +async def test_get_attribution_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_attribution_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_attribution_settings] = mock_object + + request = {} + await client.get_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_attribution_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_attribution_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetAttributionSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.AttributionSettings( + name='name_value', + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + )) + response = await client.get_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAttributionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AttributionSettings) + assert response.name == 'name_value' + assert response.acquisition_conversion_event_lookback_window == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + assert response.other_conversion_event_lookback_window == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + assert response.reporting_attribution_model == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + assert response.ads_web_conversion_data_export_scope == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + + +@pytest.mark.asyncio +async def test_get_attribution_settings_async_from_dict(): + await test_get_attribution_settings_async(request_type=dict) + + +def test_get_attribution_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAttributionSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attribution_settings), + '__call__') as call: + call.return_value = resources.AttributionSettings() + client.get_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_attribution_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAttributionSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attribution_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AttributionSettings()) + await client.get_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_attribution_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AttributionSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_attribution_settings( + 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_attribution_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_attribution_settings( + analytics_admin.GetAttributionSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_attribution_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AttributionSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AttributionSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_attribution_settings( + 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_attribution_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_attribution_settings( + analytics_admin.GetAttributionSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAttributionSettingsRequest, + dict, +]) +def test_update_attribution_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AttributionSettings( + name='name_value', + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + ) + response = client.update_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAttributionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AttributionSettings) + assert response.name == 'name_value' + assert response.acquisition_conversion_event_lookback_window == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + assert response.other_conversion_event_lookback_window == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + assert response.reporting_attribution_model == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + assert response.ads_web_conversion_data_export_scope == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + + +def test_update_attribution_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_attribution_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_attribution_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAttributionSettingsRequest() + + +def test_update_attribution_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateAttributionSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attribution_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_attribution_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAttributionSettingsRequest( + ) + +def test_update_attribution_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_attribution_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_attribution_settings] = mock_rpc + request = {} + client.update_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_attribution_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_attribution_settings_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 = AnalyticsAdminServiceAsyncClient( + 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_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AttributionSettings( + name='name_value', + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + )) + response = await client.update_attribution_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAttributionSettingsRequest() + +@pytest.mark.asyncio +async def test_update_attribution_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_attribution_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_attribution_settings] = mock_object + + request = {} + await client.update_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_attribution_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_attribution_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateAttributionSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.AttributionSettings( + name='name_value', + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + )) + response = await client.update_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAttributionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AttributionSettings) + assert response.name == 'name_value' + assert response.acquisition_conversion_event_lookback_window == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + assert response.other_conversion_event_lookback_window == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + assert response.reporting_attribution_model == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + assert response.ads_web_conversion_data_export_scope == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + + +@pytest.mark.asyncio +async def test_update_attribution_settings_async_from_dict(): + await test_update_attribution_settings_async(request_type=dict) + + +def test_update_attribution_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAttributionSettingsRequest() + + request.attribution_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attribution_settings), + '__call__') as call: + call.return_value = resources.AttributionSettings() + client.update_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attribution_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_attribution_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAttributionSettingsRequest() + + request.attribution_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attribution_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AttributionSettings()) + await client.update_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'attribution_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_attribution_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AttributionSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_attribution_settings( + attribution_settings=resources.AttributionSettings(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].attribution_settings + mock_val = resources.AttributionSettings(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_attribution_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_attribution_settings( + analytics_admin.UpdateAttributionSettingsRequest(), + attribution_settings=resources.AttributionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_attribution_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_attribution_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AttributionSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AttributionSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_attribution_settings( + attribution_settings=resources.AttributionSettings(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].attribution_settings + mock_val = resources.AttributionSettings(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_attribution_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_attribution_settings( + analytics_admin.UpdateAttributionSettingsRequest(), + attribution_settings=resources.AttributionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.RunAccessReportRequest, + dict, +]) +def test_run_access_report(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.RunAccessReportResponse( + row_count=992, + ) + response = client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.RunAccessReportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.RunAccessReportResponse) + assert response.row_count == 992 + + +def test_run_access_report_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_access_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.RunAccessReportRequest() + + +def test_run_access_report_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.RunAccessReportRequest( + entity='entity_value', + time_zone='time_zone_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_access_report(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.RunAccessReportRequest( + entity='entity_value', + time_zone='time_zone_value', + ) + +def test_run_access_report_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_access_report in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_access_report] = mock_rpc + request = {} + client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_access_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_access_report_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 = AnalyticsAdminServiceAsyncClient( + 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.run_access_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.RunAccessReportResponse( + row_count=992, + )) + response = await client.run_access_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.RunAccessReportRequest() + +@pytest.mark.asyncio +async def test_run_access_report_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.run_access_report in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.run_access_report] = mock_object + + request = {} + await client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.run_access_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_run_access_report_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.RunAccessReportRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.RunAccessReportResponse( + row_count=992, + )) + response = await client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.RunAccessReportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.RunAccessReportResponse) + assert response.row_count == 992 + + +@pytest.mark.asyncio +async def test_run_access_report_async_from_dict(): + await test_run_access_report_async(request_type=dict) + + +def test_run_access_report_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.RunAccessReportRequest() + + request.entity = 'entity_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + call.return_value = analytics_admin.RunAccessReportResponse() + client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entity=entity_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_access_report_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.RunAccessReportRequest() + + request.entity = 'entity_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.RunAccessReportResponse()) + await client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entity=entity_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateAccessBindingRequest, + dict, +]) +def test_create_access_binding(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding( + name='name_value', + roles=['roles_value'], + user='user_value', + ) + response = client.create_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == 'name_value' + assert response.roles == ['roles_value'] + + +def test_create_access_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_access_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_access_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateAccessBindingRequest() + + +def test_create_access_binding_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateAccessBindingRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_access_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_access_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateAccessBindingRequest( + parent='parent_value', + ) + +def test_create_access_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_access_binding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_access_binding] = mock_rpc + request = {} + client.create_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_access_binding_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 = AnalyticsAdminServiceAsyncClient( + 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding( + name='name_value', + roles=['roles_value'], + )) + response = await client.create_access_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateAccessBindingRequest() + +@pytest.mark.asyncio +async def test_create_access_binding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_access_binding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_access_binding] = mock_object + + request = {} + await client.create_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_access_binding_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateAccessBindingRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding( + name='name_value', + roles=['roles_value'], + )) + response = await client.create_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == 'name_value' + assert response.roles == ['roles_value'] + + +@pytest.mark.asyncio +async def test_create_access_binding_async_from_dict(): + await test_create_access_binding_async(request_type=dict) + + +def test_create_access_binding_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateAccessBindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_access_binding), + '__call__') as call: + call.return_value = resources.AccessBinding() + client.create_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_access_binding_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateAccessBindingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_access_binding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding()) + await client.create_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_access_binding_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_access_binding( + parent='parent_value', + access_binding=resources.AccessBinding(user='user_value'), + ) + + # Establish that the 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].access_binding + mock_val = resources.AccessBinding(user='user_value') + assert arg == mock_val + + +def test_create_access_binding_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_access_binding( + analytics_admin.CreateAccessBindingRequest(), + parent='parent_value', + access_binding=resources.AccessBinding(user='user_value'), + ) + +@pytest.mark.asyncio +async def test_create_access_binding_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_access_binding( + parent='parent_value', + access_binding=resources.AccessBinding(user='user_value'), + ) + + # Establish that 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].access_binding + mock_val = resources.AccessBinding(user='user_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_access_binding_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_access_binding( + analytics_admin.CreateAccessBindingRequest(), + parent='parent_value', + access_binding=resources.AccessBinding(user='user_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAccessBindingRequest, + dict, +]) +def test_get_access_binding(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding( + name='name_value', + roles=['roles_value'], + user='user_value', + ) + response = client.get_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == 'name_value' + assert response.roles == ['roles_value'] + + +def test_get_access_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_access_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_access_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccessBindingRequest() + + +def test_get_access_binding_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetAccessBindingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_access_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccessBindingRequest( + name='name_value', + ) + +def test_get_access_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_access_binding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_access_binding] = mock_rpc + request = {} + client.get_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_access_binding_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 = AnalyticsAdminServiceAsyncClient( + 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding( + name='name_value', + roles=['roles_value'], + )) + response = await client.get_access_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccessBindingRequest() + +@pytest.mark.asyncio +async def test_get_access_binding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_access_binding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_access_binding] = mock_object + + request = {} + await client.get_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_access_binding_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetAccessBindingRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding( + name='name_value', + roles=['roles_value'], + )) + response = await client.get_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == 'name_value' + assert response.roles == ['roles_value'] + + +@pytest.mark.asyncio +async def test_get_access_binding_async_from_dict(): + await test_get_access_binding_async(request_type=dict) + + +def test_get_access_binding_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAccessBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), + '__call__') as call: + call.return_value = resources.AccessBinding() + client.get_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_access_binding_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAccessBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding()) + await client.get_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_access_binding_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_access_binding( + 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_access_binding_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_access_binding( + analytics_admin.GetAccessBindingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_access_binding_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_access_binding( + 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_access_binding_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_access_binding( + analytics_admin.GetAccessBindingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAccessBindingRequest, + dict, +]) +def test_update_access_binding(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding( + name='name_value', + roles=['roles_value'], + user='user_value', + ) + response = client.update_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == 'name_value' + assert response.roles == ['roles_value'] + + +def test_update_access_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_access_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_access_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAccessBindingRequest() + + +def test_update_access_binding_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateAccessBindingRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_access_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_access_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAccessBindingRequest( + ) + +def test_update_access_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_access_binding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_access_binding] = mock_rpc + request = {} + client.update_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_access_binding_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 = AnalyticsAdminServiceAsyncClient( + 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding( + name='name_value', + roles=['roles_value'], + )) + response = await client.update_access_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAccessBindingRequest() + +@pytest.mark.asyncio +async def test_update_access_binding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_access_binding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_access_binding] = mock_object + + request = {} + await client.update_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_access_binding_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateAccessBindingRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding( + name='name_value', + roles=['roles_value'], + )) + response = await client.update_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == 'name_value' + assert response.roles == ['roles_value'] + + +@pytest.mark.asyncio +async def test_update_access_binding_async_from_dict(): + await test_update_access_binding_async(request_type=dict) + + +def test_update_access_binding_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAccessBindingRequest() + + request.access_binding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_access_binding), + '__call__') as call: + call.return_value = resources.AccessBinding() + client.update_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'access_binding.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_access_binding_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAccessBindingRequest() + + request.access_binding.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_access_binding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding()) + await client.update_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'access_binding.name=name_value', + ) in kw['metadata'] + + +def test_update_access_binding_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_access_binding( + access_binding=resources.AccessBinding(user='user_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].access_binding + mock_val = resources.AccessBinding(user='user_value') + assert arg == mock_val + + +def test_update_access_binding_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_access_binding( + analytics_admin.UpdateAccessBindingRequest(), + access_binding=resources.AccessBinding(user='user_value'), + ) + +@pytest.mark.asyncio +async def test_update_access_binding_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AccessBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AccessBinding()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_access_binding( + access_binding=resources.AccessBinding(user='user_value'), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].access_binding + mock_val = resources.AccessBinding(user='user_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_access_binding_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_access_binding( + analytics_admin.UpdateAccessBindingRequest(), + access_binding=resources.AccessBinding(user='user_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteAccessBindingRequest, + dict, +]) +def test_delete_access_binding(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteAccessBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_access_binding_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_access_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_access_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAccessBindingRequest() + + +def test_delete_access_binding_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteAccessBindingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_access_binding), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_access_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAccessBindingRequest( + name='name_value', + ) + +def test_delete_access_binding_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_access_binding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_access_binding] = mock_rpc + request = {} + client.delete_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_access_binding_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 = AnalyticsAdminServiceAsyncClient( + 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_access_binding() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAccessBindingRequest() + +@pytest.mark.asyncio +async def test_delete_access_binding_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_access_binding in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_access_binding] = mock_object + + request = {} + await client.delete_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_access_binding_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteAccessBindingRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_binding), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteAccessBindingRequest() + 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_access_binding_async_from_dict(): + await test_delete_access_binding_async(request_type=dict) + + +def test_delete_access_binding_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteAccessBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_access_binding), + '__call__') as call: + call.return_value = None + client.delete_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_access_binding_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteAccessBindingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_access_binding), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_access_binding_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_access_binding), + '__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_access_binding( + 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_access_binding_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_access_binding( + analytics_admin.DeleteAccessBindingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_access_binding_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_access_binding), + '__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_access_binding( + 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_access_binding_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_access_binding( + analytics_admin.DeleteAccessBindingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccessBindingsRequest, + dict, +]) +def test_list_access_bindings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAccessBindingsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccessBindingsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_access_bindings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccessBindingsRequest() + + +def test_list_access_bindings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccessBindingsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_access_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccessBindingsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_access_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_access_bindings] = mock_rpc + request = {} + client.list_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_access_bindings_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 = AnalyticsAdminServiceAsyncClient( + 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_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccessBindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccessBindingsRequest() + +@pytest.mark.asyncio +async def test_list_access_bindings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_access_bindings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_access_bindings] = mock_object + + request = {} + await client.list_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_access_bindings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListAccessBindingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccessBindingsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccessBindingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_access_bindings_async_from_dict(): + await test_list_access_bindings_async(request_type=dict) + + +def test_list_access_bindings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_bindings), + '__call__') as call: + call.return_value = analytics_admin.ListAccessBindingsResponse() + client.list_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_access_bindings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_bindings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccessBindingsResponse()) + await client.list_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_access_bindings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAccessBindingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_access_bindings( + 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_access_bindings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_access_bindings( + analytics_admin.ListAccessBindingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_access_bindings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAccessBindingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccessBindingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_access_bindings( + 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_access_bindings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_access_bindings( + analytics_admin.ListAccessBindingsRequest(), + parent='parent_value', + ) + + +def test_list_access_bindings_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_access_bindings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], + next_page_token='def', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_access_bindings(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AccessBinding) + for i in results) +def test_list_access_bindings_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_access_bindings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], + next_page_token='def', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_access_bindings(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_access_bindings_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_bindings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], + next_page_token='def', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_access_bindings(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, resources.AccessBinding) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_access_bindings_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_access_bindings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], + next_page_token='def', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + ], + ), + 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_access_bindings(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", [ + analytics_admin.BatchCreateAccessBindingsRequest, + dict, +]) +def test_batch_create_access_bindings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.BatchCreateAccessBindingsResponse( + ) + response = client.batch_create_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.BatchCreateAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.BatchCreateAccessBindingsResponse) + + +def test_batch_create_access_bindings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchCreateAccessBindingsRequest() + + +def test_batch_create_access_bindings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.BatchCreateAccessBindingsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_create_access_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchCreateAccessBindingsRequest( + parent='parent_value', + ) + +def test_batch_create_access_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_create_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_create_access_bindings] = mock_rpc + request = {} + client.batch_create_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_access_bindings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.BatchCreateAccessBindingsResponse( + )) + response = await client.batch_create_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchCreateAccessBindingsRequest() + +@pytest.mark.asyncio +async def test_batch_create_access_bindings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.batch_create_access_bindings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.batch_create_access_bindings] = mock_object + + request = {} + await client.batch_create_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.batch_create_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_create_access_bindings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.BatchCreateAccessBindingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.BatchCreateAccessBindingsResponse( + )) + response = await client.batch_create_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.BatchCreateAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.BatchCreateAccessBindingsResponse) + + +@pytest.mark.asyncio +async def test_batch_create_access_bindings_async_from_dict(): + await test_batch_create_access_bindings_async(request_type=dict) + + +def test_batch_create_access_bindings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.BatchCreateAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_access_bindings), + '__call__') as call: + call.return_value = analytics_admin.BatchCreateAccessBindingsResponse() + client.batch_create_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_create_access_bindings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.BatchCreateAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_access_bindings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.BatchCreateAccessBindingsResponse()) + await client.batch_create_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + analytics_admin.BatchGetAccessBindingsRequest, + dict, +]) +def test_batch_get_access_bindings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.BatchGetAccessBindingsResponse( + ) + response = client.batch_get_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.BatchGetAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.BatchGetAccessBindingsResponse) + + +def test_batch_get_access_bindings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_get_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchGetAccessBindingsRequest() + + +def test_batch_get_access_bindings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.BatchGetAccessBindingsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_get_access_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchGetAccessBindingsRequest( + parent='parent_value', + ) + +def test_batch_get_access_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_get_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_get_access_bindings] = mock_rpc + request = {} + client.batch_get_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_get_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_get_access_bindings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.BatchGetAccessBindingsResponse( + )) + response = await client.batch_get_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchGetAccessBindingsRequest() + +@pytest.mark.asyncio +async def test_batch_get_access_bindings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.batch_get_access_bindings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.batch_get_access_bindings] = mock_object + + request = {} + await client.batch_get_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.batch_get_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_get_access_bindings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.BatchGetAccessBindingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.BatchGetAccessBindingsResponse( + )) + response = await client.batch_get_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.BatchGetAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.BatchGetAccessBindingsResponse) + + +@pytest.mark.asyncio +async def test_batch_get_access_bindings_async_from_dict(): + await test_batch_get_access_bindings_async(request_type=dict) + + +def test_batch_get_access_bindings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.BatchGetAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_access_bindings), + '__call__') as call: + call.return_value = analytics_admin.BatchGetAccessBindingsResponse() + client.batch_get_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_get_access_bindings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.BatchGetAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_access_bindings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.BatchGetAccessBindingsResponse()) + await client.batch_get_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + analytics_admin.BatchUpdateAccessBindingsRequest, + dict, +]) +def test_batch_update_access_bindings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.BatchUpdateAccessBindingsResponse( + ) + response = client.batch_update_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.BatchUpdateAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.BatchUpdateAccessBindingsResponse) + + +def test_batch_update_access_bindings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_update_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchUpdateAccessBindingsRequest() + + +def test_batch_update_access_bindings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.BatchUpdateAccessBindingsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_update_access_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchUpdateAccessBindingsRequest( + parent='parent_value', + ) + +def test_batch_update_access_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_update_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_update_access_bindings] = mock_rpc + request = {} + client.batch_update_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_update_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_update_access_bindings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.BatchUpdateAccessBindingsResponse( + )) + response = await client.batch_update_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchUpdateAccessBindingsRequest() + +@pytest.mark.asyncio +async def test_batch_update_access_bindings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.batch_update_access_bindings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.batch_update_access_bindings] = mock_object + + request = {} + await client.batch_update_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.batch_update_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_update_access_bindings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.BatchUpdateAccessBindingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.BatchUpdateAccessBindingsResponse( + )) + response = await client.batch_update_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.BatchUpdateAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.BatchUpdateAccessBindingsResponse) + + +@pytest.mark.asyncio +async def test_batch_update_access_bindings_async_from_dict(): + await test_batch_update_access_bindings_async(request_type=dict) + + +def test_batch_update_access_bindings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.BatchUpdateAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_access_bindings), + '__call__') as call: + call.return_value = analytics_admin.BatchUpdateAccessBindingsResponse() + client.batch_update_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_update_access_bindings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.BatchUpdateAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_access_bindings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.BatchUpdateAccessBindingsResponse()) + await client.batch_update_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + analytics_admin.BatchDeleteAccessBindingsRequest, + dict, +]) +def test_batch_delete_access_bindings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.batch_delete_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.BatchDeleteAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_batch_delete_access_bindings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_delete_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchDeleteAccessBindingsRequest() + + +def test_batch_delete_access_bindings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.BatchDeleteAccessBindingsRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_access_bindings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.batch_delete_access_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchDeleteAccessBindingsRequest( + parent='parent_value', + ) + +def test_batch_delete_access_bindings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_delete_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_delete_access_bindings] = mock_rpc + request = {} + client.batch_delete_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_delete_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_delete_access_bindings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.batch_delete_access_bindings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.BatchDeleteAccessBindingsRequest() + +@pytest.mark.asyncio +async def test_batch_delete_access_bindings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.batch_delete_access_bindings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.batch_delete_access_bindings] = mock_object + + request = {} + await client.batch_delete_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.batch_delete_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_batch_delete_access_bindings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.BatchDeleteAccessBindingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_access_bindings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.batch_delete_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.BatchDeleteAccessBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_batch_delete_access_bindings_async_from_dict(): + await test_batch_delete_access_bindings_async(request_type=dict) + + +def test_batch_delete_access_bindings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.BatchDeleteAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_access_bindings), + '__call__') as call: + call.return_value = None + client.batch_delete_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_delete_access_bindings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.BatchDeleteAccessBindingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_access_bindings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.batch_delete_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + analytics_admin.GetExpandedDataSetRequest, + dict, +]) +def test_get_expanded_data_set(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_value'], + ) + response = client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetExpandedDataSetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, expanded_data_set.ExpandedDataSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.dimension_names == ['dimension_names_value'] + assert response.metric_names == ['metric_names_value'] + + +def test_get_expanded_data_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetExpandedDataSetRequest() + + +def test_get_expanded_data_set_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetExpandedDataSetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_expanded_data_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetExpandedDataSetRequest( + name='name_value', + ) + +def test_get_expanded_data_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_expanded_data_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_expanded_data_set] = mock_rpc + request = {} + client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_expanded_data_set_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 = AnalyticsAdminServiceAsyncClient( + 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_value'], + )) + response = await client.get_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetExpandedDataSetRequest() + +@pytest.mark.asyncio +async def test_get_expanded_data_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_expanded_data_set in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_expanded_data_set] = mock_object + + request = {} + await client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_expanded_data_set_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetExpandedDataSetRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_value'], + )) + response = await client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetExpandedDataSetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, expanded_data_set.ExpandedDataSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.dimension_names == ['dimension_names_value'] + assert response.metric_names == ['metric_names_value'] + + +@pytest.mark.asyncio +async def test_get_expanded_data_set_async_from_dict(): + await test_get_expanded_data_set_async(request_type=dict) + + +def test_get_expanded_data_set_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetExpandedDataSetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), + '__call__') as call: + call.return_value = expanded_data_set.ExpandedDataSet() + client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_expanded_data_set_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetExpandedDataSetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(expanded_data_set.ExpandedDataSet()) + await client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_expanded_data_set_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = expanded_data_set.ExpandedDataSet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_expanded_data_set( + 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_expanded_data_set_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_set( + analytics_admin.GetExpandedDataSetRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_expanded_data_set_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = expanded_data_set.ExpandedDataSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(expanded_data_set.ExpandedDataSet()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_expanded_data_set( + 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_expanded_data_set_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_expanded_data_set( + analytics_admin.GetExpandedDataSetRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListExpandedDataSetsRequest, + dict, +]) +def test_list_expanded_data_sets(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_sets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListExpandedDataSetsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_expanded_data_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListExpandedDataSetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExpandedDataSetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_expanded_data_sets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_sets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_expanded_data_sets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListExpandedDataSetsRequest() + + +def test_list_expanded_data_sets_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListExpandedDataSetsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_expanded_data_sets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_expanded_data_sets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListExpandedDataSetsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_expanded_data_sets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_expanded_data_sets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_expanded_data_sets] = mock_rpc + request = {} + client.list_expanded_data_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_expanded_data_sets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_expanded_data_sets_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 = AnalyticsAdminServiceAsyncClient( + 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_expanded_data_sets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListExpandedDataSetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_expanded_data_sets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListExpandedDataSetsRequest() + +@pytest.mark.asyncio +async def test_list_expanded_data_sets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_expanded_data_sets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_expanded_data_sets] = mock_object + + request = {} + await client.list_expanded_data_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_expanded_data_sets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_expanded_data_sets_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListExpandedDataSetsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_sets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListExpandedDataSetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_expanded_data_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListExpandedDataSetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExpandedDataSetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_expanded_data_sets_async_from_dict(): + await test_list_expanded_data_sets_async(request_type=dict) + + +def test_list_expanded_data_sets_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListExpandedDataSetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_expanded_data_sets), + '__call__') as call: + call.return_value = analytics_admin.ListExpandedDataSetsResponse() + client.list_expanded_data_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_expanded_data_sets_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListExpandedDataSetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_expanded_data_sets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListExpandedDataSetsResponse()) + await client.list_expanded_data_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_expanded_data_sets_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_expanded_data_sets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListExpandedDataSetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_expanded_data_sets( + 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_expanded_data_sets_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_sets( + analytics_admin.ListExpandedDataSetsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_expanded_data_sets_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_expanded_data_sets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListExpandedDataSetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListExpandedDataSetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_expanded_data_sets( + 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_expanded_data_sets_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_expanded_data_sets( + analytics_admin.ListExpandedDataSetsRequest(), + parent='parent_value', + ) + + +def test_list_expanded_data_sets_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_expanded_data_sets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='abc', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], + next_page_token='def', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='ghi', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_expanded_data_sets(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, expanded_data_set.ExpandedDataSet) + for i in results) +def test_list_expanded_data_sets_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_expanded_data_sets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='abc', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], + next_page_token='def', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='ghi', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + ), + RuntimeError, + ) + pages = list(client.list_expanded_data_sets(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_expanded_data_sets_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_expanded_data_sets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='abc', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], + next_page_token='def', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='ghi', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_expanded_data_sets(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, expanded_data_set.ExpandedDataSet) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_expanded_data_sets_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_expanded_data_sets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='abc', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], + next_page_token='def', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='ghi', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + ), + 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_expanded_data_sets(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", [ + analytics_admin.CreateExpandedDataSetRequest, + dict, +]) +def test_create_expanded_data_set(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_value'], + ) + response = client.create_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateExpandedDataSetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.dimension_names == ['dimension_names_value'] + assert response.metric_names == ['metric_names_value'] + + +def test_create_expanded_data_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateExpandedDataSetRequest() + + +def test_create_expanded_data_set_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateExpandedDataSetRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_expanded_data_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_expanded_data_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateExpandedDataSetRequest( + parent='parent_value', + ) + +def test_create_expanded_data_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_expanded_data_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_expanded_data_set] = mock_rpc + request = {} + client.create_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_expanded_data_set_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 = AnalyticsAdminServiceAsyncClient( + 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_value'], + )) + response = await client.create_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateExpandedDataSetRequest() + +@pytest.mark.asyncio +async def test_create_expanded_data_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_expanded_data_set in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_expanded_data_set] = mock_object + + request = {} + await client.create_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_expanded_data_set_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateExpandedDataSetRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gaa_expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_value'], + )) + response = await client.create_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateExpandedDataSetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.dimension_names == ['dimension_names_value'] + assert response.metric_names == ['metric_names_value'] + + +@pytest.mark.asyncio +async def test_create_expanded_data_set_async_from_dict(): + await test_create_expanded_data_set_async(request_type=dict) + + +def test_create_expanded_data_set_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateExpandedDataSetRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_expanded_data_set), + '__call__') as call: + call.return_value = gaa_expanded_data_set.ExpandedDataSet() + client.create_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_expanded_data_set_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateExpandedDataSetRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_expanded_data_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_expanded_data_set.ExpandedDataSet()) + await client.create_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_expanded_data_set_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_expanded_data_set.ExpandedDataSet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_expanded_data_set( + parent='parent_value', + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(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].expanded_data_set + mock_val = gaa_expanded_data_set.ExpandedDataSet(name='name_value') + assert arg == mock_val + + +def test_create_expanded_data_set_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_set( + analytics_admin.CreateExpandedDataSetRequest(), + parent='parent_value', + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_expanded_data_set_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_expanded_data_set.ExpandedDataSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_expanded_data_set.ExpandedDataSet()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_expanded_data_set( + parent='parent_value', + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(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].expanded_data_set + mock_val = gaa_expanded_data_set.ExpandedDataSet(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_expanded_data_set_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_expanded_data_set( + analytics_admin.CreateExpandedDataSetRequest(), + parent='parent_value', + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateExpandedDataSetRequest, + dict, +]) +def test_update_expanded_data_set(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_value'], + ) + response = client.update_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateExpandedDataSetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.dimension_names == ['dimension_names_value'] + assert response.metric_names == ['metric_names_value'] + + +def test_update_expanded_data_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateExpandedDataSetRequest() + + +def test_update_expanded_data_set_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateExpandedDataSetRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_expanded_data_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_expanded_data_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateExpandedDataSetRequest( + ) + +def test_update_expanded_data_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_expanded_data_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_expanded_data_set] = mock_rpc + request = {} + client.update_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_expanded_data_set_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 = AnalyticsAdminServiceAsyncClient( + 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_value'], + )) + response = await client.update_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateExpandedDataSetRequest() + +@pytest.mark.asyncio +async def test_update_expanded_data_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_expanded_data_set in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_expanded_data_set] = mock_object + + request = {} + await client.update_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_expanded_data_set_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateExpandedDataSetRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gaa_expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_value'], + )) + response = await client.update_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateExpandedDataSetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.dimension_names == ['dimension_names_value'] + assert response.metric_names == ['metric_names_value'] + + +@pytest.mark.asyncio +async def test_update_expanded_data_set_async_from_dict(): + await test_update_expanded_data_set_async(request_type=dict) + + +def test_update_expanded_data_set_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateExpandedDataSetRequest() + + request.expanded_data_set.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_expanded_data_set), + '__call__') as call: + call.return_value = gaa_expanded_data_set.ExpandedDataSet() + client.update_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'expanded_data_set.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_expanded_data_set_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateExpandedDataSetRequest() + + request.expanded_data_set.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_expanded_data_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_expanded_data_set.ExpandedDataSet()) + await client.update_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'expanded_data_set.name=name_value', + ) in kw['metadata'] + + +def test_update_expanded_data_set_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_expanded_data_set.ExpandedDataSet() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_expanded_data_set( + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(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].expanded_data_set + mock_val = gaa_expanded_data_set.ExpandedDataSet(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_expanded_data_set_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_set( + analytics_admin.UpdateExpandedDataSetRequest(), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_expanded_data_set_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_expanded_data_set.ExpandedDataSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_expanded_data_set.ExpandedDataSet()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_expanded_data_set( + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(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].expanded_data_set + mock_val = gaa_expanded_data_set.ExpandedDataSet(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_expanded_data_set_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_expanded_data_set( + analytics_admin.UpdateExpandedDataSetRequest(), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteExpandedDataSetRequest, + dict, +]) +def test_delete_expanded_data_set(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteExpandedDataSetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_expanded_data_set_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteExpandedDataSetRequest() + + +def test_delete_expanded_data_set_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteExpandedDataSetRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_expanded_data_set), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_expanded_data_set(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteExpandedDataSetRequest( + name='name_value', + ) + +def test_delete_expanded_data_set_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_expanded_data_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_expanded_data_set] = mock_rpc + request = {} + client.delete_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_expanded_data_set_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 = AnalyticsAdminServiceAsyncClient( + 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_expanded_data_set() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteExpandedDataSetRequest() + +@pytest.mark.asyncio +async def test_delete_expanded_data_set_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_expanded_data_set in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_expanded_data_set] = mock_object + + request = {} + await client.delete_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_expanded_data_set_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteExpandedDataSetRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_expanded_data_set), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteExpandedDataSetRequest() + 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_expanded_data_set_async_from_dict(): + await test_delete_expanded_data_set_async(request_type=dict) + + +def test_delete_expanded_data_set_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteExpandedDataSetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_expanded_data_set), + '__call__') as call: + call.return_value = None + client.delete_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_expanded_data_set_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteExpandedDataSetRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_expanded_data_set), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_expanded_data_set_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_expanded_data_set), + '__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_expanded_data_set( + 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_expanded_data_set_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_expanded_data_set( + analytics_admin.DeleteExpandedDataSetRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_expanded_data_set_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_expanded_data_set), + '__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_expanded_data_set( + 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_expanded_data_set_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_expanded_data_set( + analytics_admin.DeleteExpandedDataSetRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetChannelGroupRequest, + dict, +]) +def test_get_channel_group(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=True, + ) + response = client.get_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetChannelGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, channel_group.ChannelGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.system_defined is True + assert response.primary is True + + +def test_get_channel_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_channel_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_channel_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetChannelGroupRequest() + + +def test_get_channel_group_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetChannelGroupRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_channel_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetChannelGroupRequest( + name='name_value', + ) + +def test_get_channel_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_channel_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_channel_group] = mock_rpc + request = {} + client.get_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_channel_group_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 = AnalyticsAdminServiceAsyncClient( + 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=True, + )) + response = await client.get_channel_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetChannelGroupRequest() + +@pytest.mark.asyncio +async def test_get_channel_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_channel_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_channel_group] = mock_object + + request = {} + await client.get_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_channel_group_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetChannelGroupRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=True, + )) + response = await client.get_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetChannelGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, channel_group.ChannelGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.system_defined is True + assert response.primary is True + + +@pytest.mark.asyncio +async def test_get_channel_group_async_from_dict(): + await test_get_channel_group_async(request_type=dict) + + +def test_get_channel_group_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetChannelGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_group), + '__call__') as call: + call.return_value = channel_group.ChannelGroup() + client.get_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_channel_group_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetChannelGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel_group.ChannelGroup()) + await client.get_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_channel_group_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = channel_group.ChannelGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_channel_group( + 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_channel_group_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_channel_group( + analytics_admin.GetChannelGroupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_channel_group_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = channel_group.ChannelGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(channel_group.ChannelGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_channel_group( + 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_channel_group_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_channel_group( + analytics_admin.GetChannelGroupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListChannelGroupsRequest, + dict, +]) +def test_list_channel_groups(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListChannelGroupsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_channel_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListChannelGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelGroupsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_channel_groups_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_channel_groups), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_channel_groups() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListChannelGroupsRequest() + + +def test_list_channel_groups_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListChannelGroupsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_channel_groups(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListChannelGroupsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_channel_groups_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_channel_groups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_channel_groups] = mock_rpc + request = {} + client.list_channel_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_channel_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_channel_groups_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 = AnalyticsAdminServiceAsyncClient( + 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_channel_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListChannelGroupsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_channel_groups() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListChannelGroupsRequest() + +@pytest.mark.asyncio +async def test_list_channel_groups_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_channel_groups in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_channel_groups] = mock_object + + request = {} + await client.list_channel_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_channel_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_channel_groups_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListChannelGroupsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListChannelGroupsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_channel_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListChannelGroupsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelGroupsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_channel_groups_async_from_dict(): + await test_list_channel_groups_async(request_type=dict) + + +def test_list_channel_groups_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListChannelGroupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), + '__call__') as call: + call.return_value = analytics_admin.ListChannelGroupsResponse() + client.list_channel_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_channel_groups_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListChannelGroupsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListChannelGroupsResponse()) + await client.list_channel_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_channel_groups_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListChannelGroupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_channel_groups( + 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_channel_groups_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_channel_groups( + analytics_admin.ListChannelGroupsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_channel_groups_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListChannelGroupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListChannelGroupsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_channel_groups( + 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_channel_groups_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_channel_groups( + analytics_admin.ListChannelGroupsRequest(), + parent='parent_value', + ) + + +def test_list_channel_groups_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_channel_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token='abc', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token='def', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token='ghi', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_channel_groups(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, channel_group.ChannelGroup) + for i in results) +def test_list_channel_groups_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_channel_groups), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token='abc', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token='def', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token='ghi', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_channel_groups(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_channel_groups_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token='abc', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token='def', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token='ghi', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_channel_groups(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, channel_group.ChannelGroup) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_channel_groups_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_channel_groups), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token='abc', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token='def', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token='ghi', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + 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_channel_groups(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", [ + analytics_admin.CreateChannelGroupRequest, + dict, +]) +def test_create_channel_group(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=True, + ) + response = client.create_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateChannelGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_channel_group.ChannelGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.system_defined is True + assert response.primary is True + + +def test_create_channel_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_channel_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_channel_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateChannelGroupRequest() + + +def test_create_channel_group_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateChannelGroupRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_channel_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateChannelGroupRequest( + parent='parent_value', + ) + +def test_create_channel_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_channel_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_channel_group] = mock_rpc + request = {} + client.create_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_channel_group_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 = AnalyticsAdminServiceAsyncClient( + 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=True, + )) + response = await client.create_channel_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateChannelGroupRequest() + +@pytest.mark.asyncio +async def test_create_channel_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_channel_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_channel_group] = mock_object + + request = {} + await client.create_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_channel_group_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateChannelGroupRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gaa_channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=True, + )) + response = await client.create_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateChannelGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_channel_group.ChannelGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.system_defined is True + assert response.primary is True + + +@pytest.mark.asyncio +async def test_create_channel_group_async_from_dict(): + await test_create_channel_group_async(request_type=dict) + + +def test_create_channel_group_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateChannelGroupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_group), + '__call__') as call: + call.return_value = gaa_channel_group.ChannelGroup() + client.create_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_channel_group_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateChannelGroupRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_channel_group.ChannelGroup()) + await client.create_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_channel_group_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_channel_group.ChannelGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_channel_group( + parent='parent_value', + channel_group=gaa_channel_group.ChannelGroup(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].channel_group + mock_val = gaa_channel_group.ChannelGroup(name='name_value') + assert arg == mock_val + + +def test_create_channel_group_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_channel_group( + analytics_admin.CreateChannelGroupRequest(), + parent='parent_value', + channel_group=gaa_channel_group.ChannelGroup(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_channel_group_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_channel_group.ChannelGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_channel_group.ChannelGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_channel_group( + parent='parent_value', + channel_group=gaa_channel_group.ChannelGroup(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].channel_group + mock_val = gaa_channel_group.ChannelGroup(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_channel_group_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_channel_group( + analytics_admin.CreateChannelGroupRequest(), + parent='parent_value', + channel_group=gaa_channel_group.ChannelGroup(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateChannelGroupRequest, + dict, +]) +def test_update_channel_group(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=True, + ) + response = client.update_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateChannelGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_channel_group.ChannelGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.system_defined is True + assert response.primary is True + + +def test_update_channel_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_channel_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_channel_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateChannelGroupRequest() + + +def test_update_channel_group_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateChannelGroupRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_channel_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateChannelGroupRequest( + ) + +def test_update_channel_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_channel_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_channel_group] = mock_rpc + request = {} + client.update_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_channel_group_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 = AnalyticsAdminServiceAsyncClient( + 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=True, + )) + response = await client.update_channel_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateChannelGroupRequest() + +@pytest.mark.asyncio +async def test_update_channel_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_channel_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_channel_group] = mock_object + + request = {} + await client.update_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_channel_group_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateChannelGroupRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gaa_channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=True, + )) + response = await client.update_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateChannelGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_channel_group.ChannelGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.system_defined is True + assert response.primary is True + + +@pytest.mark.asyncio +async def test_update_channel_group_async_from_dict(): + await test_update_channel_group_async(request_type=dict) + + +def test_update_channel_group_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateChannelGroupRequest() + + request.channel_group.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel_group), + '__call__') as call: + call.return_value = gaa_channel_group.ChannelGroup() + client.update_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'channel_group.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_channel_group_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateChannelGroupRequest() + + request.channel_group.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_channel_group.ChannelGroup()) + await client.update_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'channel_group.name=name_value', + ) in kw['metadata'] + + +def test_update_channel_group_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_channel_group.ChannelGroup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_channel_group( + channel_group=gaa_channel_group.ChannelGroup(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].channel_group + mock_val = gaa_channel_group.ChannelGroup(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_channel_group_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_channel_group( + analytics_admin.UpdateChannelGroupRequest(), + channel_group=gaa_channel_group.ChannelGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_channel_group_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_channel_group.ChannelGroup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_channel_group.ChannelGroup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_channel_group( + channel_group=gaa_channel_group.ChannelGroup(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].channel_group + mock_val = gaa_channel_group.ChannelGroup(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_channel_group_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_channel_group( + analytics_admin.UpdateChannelGroupRequest(), + channel_group=gaa_channel_group.ChannelGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteChannelGroupRequest, + dict, +]) +def test_delete_channel_group(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteChannelGroupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_channel_group_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_channel_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_channel_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteChannelGroupRequest() + + +def test_delete_channel_group_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteChannelGroupRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_group), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_channel_group(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteChannelGroupRequest( + name='name_value', + ) + +def test_delete_channel_group_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_channel_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_channel_group] = mock_rpc + request = {} + client.delete_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_channel_group_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 = AnalyticsAdminServiceAsyncClient( + 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_channel_group() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteChannelGroupRequest() + +@pytest.mark.asyncio +async def test_delete_channel_group_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_channel_group in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_channel_group] = mock_object + + request = {} + await client.delete_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_channel_group_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteChannelGroupRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_channel_group), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteChannelGroupRequest() + 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_channel_group_async_from_dict(): + await test_delete_channel_group_async(request_type=dict) + + +def test_delete_channel_group_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteChannelGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_group), + '__call__') as call: + call.return_value = None + client.delete_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_channel_group_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteChannelGroupRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_group), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_channel_group_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_group), + '__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_channel_group( + 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_channel_group_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_channel_group( + analytics_admin.DeleteChannelGroupRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_channel_group_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_channel_group), + '__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_channel_group( + 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_channel_group_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_channel_group( + analytics_admin.DeleteChannelGroupRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, + dict, +]) +def test_set_automated_ga4_configuration_opt_out(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_automated_ga4_configuration_opt_out), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse( + ) + response = client.set_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse) + + +def test_set_automated_ga4_configuration_opt_out_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_automated_ga4_configuration_opt_out), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_automated_ga4_configuration_opt_out() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + + +def test_set_automated_ga4_configuration_opt_out_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest( + property='property_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.set_automated_ga4_configuration_opt_out), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.set_automated_ga4_configuration_opt_out(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest( + property='property_value', + ) + +def test_set_automated_ga4_configuration_opt_out_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_automated_ga4_configuration_opt_out in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_automated_ga4_configuration_opt_out] = mock_rpc + request = {} + client.set_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_automated_ga4_configuration_opt_out(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_set_automated_ga4_configuration_opt_out_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 = AnalyticsAdminServiceAsyncClient( + 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_automated_ga4_configuration_opt_out), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse( + )) + response = await client.set_automated_ga4_configuration_opt_out() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + +@pytest.mark.asyncio +async def test_set_automated_ga4_configuration_opt_out_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.set_automated_ga4_configuration_opt_out in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.set_automated_ga4_configuration_opt_out] = mock_object + + request = {} + await client.set_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.set_automated_ga4_configuration_opt_out(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_set_automated_ga4_configuration_opt_out_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_automated_ga4_configuration_opt_out), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse( + )) + response = await client.set_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse) + + +@pytest.mark.asyncio +async def test_set_automated_ga4_configuration_opt_out_async_from_dict(): + await test_set_automated_ga4_configuration_opt_out_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, + dict, +]) +def test_fetch_automated_ga4_configuration_opt_out(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_automated_ga4_configuration_opt_out), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( + opt_out=True, + ) + response = client.fetch_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse) + assert response.opt_out is True + + +def test_fetch_automated_ga4_configuration_opt_out_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_automated_ga4_configuration_opt_out), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.fetch_automated_ga4_configuration_opt_out() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() + + +def test_fetch_automated_ga4_configuration_opt_out_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( + property='property_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_automated_ga4_configuration_opt_out), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.fetch_automated_ga4_configuration_opt_out(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest( + property='property_value', + ) + +def test_fetch_automated_ga4_configuration_opt_out_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.fetch_automated_ga4_configuration_opt_out in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.fetch_automated_ga4_configuration_opt_out] = mock_rpc + request = {} + client.fetch_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_automated_ga4_configuration_opt_out(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_automated_ga4_configuration_opt_out_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 = AnalyticsAdminServiceAsyncClient( + 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.fetch_automated_ga4_configuration_opt_out), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( + opt_out=True, + )) + response = await client.fetch_automated_ga4_configuration_opt_out() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() + +@pytest.mark.asyncio +async def test_fetch_automated_ga4_configuration_opt_out_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.fetch_automated_ga4_configuration_opt_out in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.fetch_automated_ga4_configuration_opt_out] = mock_object + + request = {} + await client.fetch_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.fetch_automated_ga4_configuration_opt_out(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_automated_ga4_configuration_opt_out_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_automated_ga4_configuration_opt_out), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( + opt_out=True, + )) + response = await client.fetch_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse) + assert response.opt_out is True + + +@pytest.mark.asyncio +async def test_fetch_automated_ga4_configuration_opt_out_async_from_dict(): + await test_fetch_automated_ga4_configuration_opt_out_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateBigQueryLinkRequest, + dict, +]) +def test_create_big_query_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_value', + ) + response = client.create_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateBigQueryLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.BigQueryLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ['export_streams_value'] + assert response.excluded_events == ['excluded_events_value'] + assert response.dataset_location == 'dataset_location_value' + + +def test_create_big_query_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_big_query_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateBigQueryLinkRequest() + + +def test_create_big_query_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateBigQueryLinkRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_big_query_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateBigQueryLinkRequest( + parent='parent_value', + ) + +def test_create_big_query_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_big_query_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_big_query_link] = mock_rpc + request = {} + client.create_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_big_query_link_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 = AnalyticsAdminServiceAsyncClient( + 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_value', + )) + response = await client.create_big_query_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateBigQueryLinkRequest() + +@pytest.mark.asyncio +async def test_create_big_query_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_big_query_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_big_query_link] = mock_object + + request = {} + await client.create_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_big_query_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateBigQueryLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_value', + )) + response = await client.create_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateBigQueryLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.BigQueryLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ['export_streams_value'] + assert response.excluded_events == ['excluded_events_value'] + assert response.dataset_location == 'dataset_location_value' + + +@pytest.mark.asyncio +async def test_create_big_query_link_async_from_dict(): + await test_create_big_query_link_async(request_type=dict) + + +def test_create_big_query_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateBigQueryLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_link), + '__call__') as call: + call.return_value = resources.BigQueryLink() + client.create_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_big_query_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateBigQueryLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink()) + await client.create_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_big_query_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_big_query_link( + parent='parent_value', + bigquery_link=resources.BigQueryLink(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].bigquery_link + mock_val = resources.BigQueryLink(name='name_value') + assert arg == mock_val + + +def test_create_big_query_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_big_query_link( + analytics_admin.CreateBigQueryLinkRequest(), + parent='parent_value', + bigquery_link=resources.BigQueryLink(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_big_query_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_big_query_link( + parent='parent_value', + bigquery_link=resources.BigQueryLink(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].bigquery_link + mock_val = resources.BigQueryLink(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_big_query_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_big_query_link( + analytics_admin.CreateBigQueryLinkRequest(), + parent='parent_value', + bigquery_link=resources.BigQueryLink(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetBigQueryLinkRequest, + dict, +]) +def test_get_big_query_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_value', + ) + response = client.get_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetBigQueryLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.BigQueryLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ['export_streams_value'] + assert response.excluded_events == ['excluded_events_value'] + assert response.dataset_location == 'dataset_location_value' + + +def test_get_big_query_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_big_query_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetBigQueryLinkRequest() + + +def test_get_big_query_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetBigQueryLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_big_query_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetBigQueryLinkRequest( + name='name_value', + ) + +def test_get_big_query_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_link] = mock_rpc + request = {} + client.get_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_link_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 = AnalyticsAdminServiceAsyncClient( + 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_value', + )) + response = await client.get_big_query_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetBigQueryLinkRequest() + +@pytest.mark.asyncio +async def test_get_big_query_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_big_query_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_big_query_link] = mock_object + + request = {} + await client.get_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_big_query_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetBigQueryLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_value', + )) + response = await client.get_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetBigQueryLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.BigQueryLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ['export_streams_value'] + assert response.excluded_events == ['excluded_events_value'] + assert response.dataset_location == 'dataset_location_value' + + +@pytest.mark.asyncio +async def test_get_big_query_link_async_from_dict(): + await test_get_big_query_link_async(request_type=dict) + + +def test_get_big_query_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetBigQueryLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_link), + '__call__') as call: + call.return_value = resources.BigQueryLink() + client.get_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_big_query_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetBigQueryLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink()) + await client.get_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_big_query_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_big_query_link( + 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_big_query_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_big_query_link( + analytics_admin.GetBigQueryLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_big_query_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_big_query_link( + 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_big_query_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_big_query_link( + analytics_admin.GetBigQueryLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListBigQueryLinksRequest, + dict, +]) +def test_list_big_query_links(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListBigQueryLinksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_big_query_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListBigQueryLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryLinksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_big_query_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_big_query_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListBigQueryLinksRequest() + + +def test_list_big_query_links_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListBigQueryLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_big_query_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListBigQueryLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_big_query_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_links] = mock_rpc + request = {} + client.list_big_query_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_links_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 = AnalyticsAdminServiceAsyncClient( + 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_big_query_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListBigQueryLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListBigQueryLinksRequest() + +@pytest.mark.asyncio +async def test_list_big_query_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_big_query_links in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_big_query_links] = mock_object + + request = {} + await client.list_big_query_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_big_query_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_big_query_links_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListBigQueryLinksRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListBigQueryLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_big_query_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListBigQueryLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryLinksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_big_query_links_async_from_dict(): + await test_list_big_query_links_async(request_type=dict) + + +def test_list_big_query_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListBigQueryLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), + '__call__') as call: + call.return_value = analytics_admin.ListBigQueryLinksResponse() + client.list_big_query_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_big_query_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListBigQueryLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListBigQueryLinksResponse()) + await client.list_big_query_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_big_query_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListBigQueryLinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_big_query_links( + 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_big_query_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_big_query_links( + analytics_admin.ListBigQueryLinksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_big_query_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListBigQueryLinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListBigQueryLinksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_big_query_links( + 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_big_query_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_big_query_links( + analytics_admin.ListBigQueryLinksRequest(), + parent='parent_value', + ) + + +def test_list_big_query_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_big_query_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token='def', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_big_query_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.BigQueryLink) + for i in results) +def test_list_big_query_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_big_query_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token='def', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_big_query_links(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_big_query_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token='def', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_big_query_links(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, resources.BigQueryLink) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_big_query_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_big_query_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token='def', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + 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_big_query_links(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", [ + analytics_admin.DeleteBigQueryLinkRequest, + dict, +]) +def test_delete_big_query_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteBigQueryLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_big_query_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_big_query_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteBigQueryLinkRequest() + + +def test_delete_big_query_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteBigQueryLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_big_query_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteBigQueryLinkRequest( + name='name_value', + ) + +def test_delete_big_query_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_big_query_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_big_query_link] = mock_rpc + request = {} + client.delete_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_big_query_link_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 = AnalyticsAdminServiceAsyncClient( + 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteBigQueryLinkRequest() + +@pytest.mark.asyncio +async def test_delete_big_query_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_big_query_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_big_query_link] = mock_object + + request = {} + await client.delete_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_big_query_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteBigQueryLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteBigQueryLinkRequest() + 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_big_query_link_async_from_dict(): + await test_delete_big_query_link_async(request_type=dict) + + +def test_delete_big_query_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteBigQueryLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_link), + '__call__') as call: + call.return_value = None + client.delete_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_big_query_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteBigQueryLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_big_query_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_link), + '__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_big_query_link( + 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_big_query_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_big_query_link( + analytics_admin.DeleteBigQueryLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_big_query_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_big_query_link), + '__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_big_query_link( + 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_big_query_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_big_query_link( + analytics_admin.DeleteBigQueryLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateBigQueryLinkRequest, + dict, +]) +def test_update_big_query_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_value', + ) + response = client.update_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateBigQueryLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.BigQueryLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ['export_streams_value'] + assert response.excluded_events == ['excluded_events_value'] + assert response.dataset_location == 'dataset_location_value' + + +def test_update_big_query_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_big_query_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateBigQueryLinkRequest() + + +def test_update_big_query_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateBigQueryLinkRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_big_query_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateBigQueryLinkRequest( + ) + +def test_update_big_query_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_big_query_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_link] = mock_rpc + request = {} + client.update_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_big_query_link_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 = AnalyticsAdminServiceAsyncClient( + 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_value', + )) + response = await client.update_big_query_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateBigQueryLinkRequest() + +@pytest.mark.asyncio +async def test_update_big_query_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_big_query_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_big_query_link] = mock_object + + request = {} + await client.update_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_big_query_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateBigQueryLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_value', + )) + response = await client.update_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateBigQueryLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.BigQueryLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ['export_streams_value'] + assert response.excluded_events == ['excluded_events_value'] + assert response.dataset_location == 'dataset_location_value' + + +@pytest.mark.asyncio +async def test_update_big_query_link_async_from_dict(): + await test_update_big_query_link_async(request_type=dict) + + +def test_update_big_query_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateBigQueryLinkRequest() + + request.bigquery_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_link), + '__call__') as call: + call.return_value = resources.BigQueryLink() + client.update_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'bigquery_link.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_big_query_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateBigQueryLinkRequest() + + request.bigquery_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink()) + await client.update_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'bigquery_link.name=name_value', + ) in kw['metadata'] + + +def test_update_big_query_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_big_query_link( + bigquery_link=resources.BigQueryLink(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].bigquery_link + mock_val = resources.BigQueryLink(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_big_query_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_big_query_link( + analytics_admin.UpdateBigQueryLinkRequest(), + bigquery_link=resources.BigQueryLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_big_query_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_big_query_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.BigQueryLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.BigQueryLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_big_query_link( + bigquery_link=resources.BigQueryLink(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].bigquery_link + mock_val = resources.BigQueryLink(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_big_query_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_big_query_link( + analytics_admin.UpdateBigQueryLinkRequest(), + bigquery_link=resources.BigQueryLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetEnhancedMeasurementSettingsRequest, + dict, +]) +def test_get_enhanced_measurement_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.EnhancedMeasurementSettings( + name='name_value', + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter='search_query_parameter_value', + uri_query_parameter='uri_query_parameter_value', + ) + response = client.get_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == 'name_value' + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == 'search_query_parameter_value' + assert response.uri_query_parameter == 'uri_query_parameter_value' + + +def test_get_enhanced_measurement_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_enhanced_measurement_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_enhanced_measurement_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEnhancedMeasurementSettingsRequest() + + +def test_get_enhanced_measurement_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetEnhancedMeasurementSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enhanced_measurement_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_enhanced_measurement_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEnhancedMeasurementSettingsRequest( + name='name_value', + ) + +def test_get_enhanced_measurement_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_enhanced_measurement_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_enhanced_measurement_settings] = mock_rpc + request = {} + client.get_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_enhanced_measurement_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_enhanced_measurement_settings_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 = AnalyticsAdminServiceAsyncClient( + 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_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.EnhancedMeasurementSettings( + name='name_value', + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter='search_query_parameter_value', + uri_query_parameter='uri_query_parameter_value', + )) + response = await client.get_enhanced_measurement_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEnhancedMeasurementSettingsRequest() + +@pytest.mark.asyncio +async def test_get_enhanced_measurement_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_enhanced_measurement_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_enhanced_measurement_settings] = mock_object + + request = {} + await client.get_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_enhanced_measurement_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_enhanced_measurement_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetEnhancedMeasurementSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.EnhancedMeasurementSettings( + name='name_value', + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter='search_query_parameter_value', + uri_query_parameter='uri_query_parameter_value', + )) + response = await client.get_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == 'name_value' + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == 'search_query_parameter_value' + assert response.uri_query_parameter == 'uri_query_parameter_value' + + +@pytest.mark.asyncio +async def test_get_enhanced_measurement_settings_async_from_dict(): + await test_get_enhanced_measurement_settings_async(request_type=dict) + + +def test_get_enhanced_measurement_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enhanced_measurement_settings), + '__call__') as call: + call.return_value = resources.EnhancedMeasurementSettings() + client.get_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_enhanced_measurement_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enhanced_measurement_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.EnhancedMeasurementSettings()) + await client.get_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_enhanced_measurement_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.EnhancedMeasurementSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_enhanced_measurement_settings( + 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_enhanced_measurement_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_enhanced_measurement_settings( + analytics_admin.GetEnhancedMeasurementSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_enhanced_measurement_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.EnhancedMeasurementSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.EnhancedMeasurementSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_enhanced_measurement_settings( + 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_enhanced_measurement_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_enhanced_measurement_settings( + analytics_admin.GetEnhancedMeasurementSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateEnhancedMeasurementSettingsRequest, + dict, +]) +def test_update_enhanced_measurement_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.EnhancedMeasurementSettings( + name='name_value', + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter='search_query_parameter_value', + uri_query_parameter='uri_query_parameter_value', + ) + response = client.update_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == 'name_value' + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == 'search_query_parameter_value' + assert response.uri_query_parameter == 'uri_query_parameter_value' + + +def test_update_enhanced_measurement_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_enhanced_measurement_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_enhanced_measurement_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + + +def test_update_enhanced_measurement_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateEnhancedMeasurementSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enhanced_measurement_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_enhanced_measurement_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateEnhancedMeasurementSettingsRequest( + ) + +def test_update_enhanced_measurement_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_enhanced_measurement_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_enhanced_measurement_settings] = mock_rpc + request = {} + client.update_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_enhanced_measurement_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_enhanced_measurement_settings_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 = AnalyticsAdminServiceAsyncClient( + 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_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.EnhancedMeasurementSettings( + name='name_value', + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter='search_query_parameter_value', + uri_query_parameter='uri_query_parameter_value', + )) + response = await client.update_enhanced_measurement_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + +@pytest.mark.asyncio +async def test_update_enhanced_measurement_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_enhanced_measurement_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_enhanced_measurement_settings] = mock_object + + request = {} + await client.update_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_enhanced_measurement_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_enhanced_measurement_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateEnhancedMeasurementSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.EnhancedMeasurementSettings( + name='name_value', + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter='search_query_parameter_value', + uri_query_parameter='uri_query_parameter_value', + )) + response = await client.update_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == 'name_value' + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == 'search_query_parameter_value' + assert response.uri_query_parameter == 'uri_query_parameter_value' + + +@pytest.mark.asyncio +async def test_update_enhanced_measurement_settings_async_from_dict(): + await test_update_enhanced_measurement_settings_async(request_type=dict) + + +def test_update_enhanced_measurement_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + + request.enhanced_measurement_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enhanced_measurement_settings), + '__call__') as call: + call.return_value = resources.EnhancedMeasurementSettings() + client.update_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'enhanced_measurement_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_enhanced_measurement_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + + request.enhanced_measurement_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enhanced_measurement_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.EnhancedMeasurementSettings()) + await client.update_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'enhanced_measurement_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_enhanced_measurement_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.EnhancedMeasurementSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_enhanced_measurement_settings( + enhanced_measurement_settings=resources.EnhancedMeasurementSettings(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].enhanced_measurement_settings + mock_val = resources.EnhancedMeasurementSettings(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_enhanced_measurement_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_enhanced_measurement_settings( + analytics_admin.UpdateEnhancedMeasurementSettingsRequest(), + enhanced_measurement_settings=resources.EnhancedMeasurementSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_enhanced_measurement_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_enhanced_measurement_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.EnhancedMeasurementSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.EnhancedMeasurementSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_enhanced_measurement_settings( + enhanced_measurement_settings=resources.EnhancedMeasurementSettings(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].enhanced_measurement_settings + mock_val = resources.EnhancedMeasurementSettings(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_enhanced_measurement_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_enhanced_measurement_settings( + analytics_admin.UpdateEnhancedMeasurementSettingsRequest(), + enhanced_measurement_settings=resources.EnhancedMeasurementSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateConnectedSiteTagRequest, + dict, +]) +def test_create_connected_site_tag(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connected_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.CreateConnectedSiteTagResponse( + ) + response = client.create_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateConnectedSiteTagRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.CreateConnectedSiteTagResponse) + + +def test_create_connected_site_tag_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_connected_site_tag), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_connected_site_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateConnectedSiteTagRequest() + + +def test_create_connected_site_tag_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateConnectedSiteTagRequest( + property='property_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_connected_site_tag), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_connected_site_tag(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateConnectedSiteTagRequest( + property='property_value', + ) + +def test_create_connected_site_tag_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_connected_site_tag in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_connected_site_tag] = mock_rpc + request = {} + client.create_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_connected_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_connected_site_tag_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 = AnalyticsAdminServiceAsyncClient( + 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_connected_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.CreateConnectedSiteTagResponse( + )) + response = await client.create_connected_site_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateConnectedSiteTagRequest() + +@pytest.mark.asyncio +async def test_create_connected_site_tag_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_connected_site_tag in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_connected_site_tag] = mock_object + + request = {} + await client.create_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_connected_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_connected_site_tag_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateConnectedSiteTagRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connected_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.CreateConnectedSiteTagResponse( + )) + response = await client.create_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateConnectedSiteTagRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.CreateConnectedSiteTagResponse) + + +@pytest.mark.asyncio +async def test_create_connected_site_tag_async_from_dict(): + await test_create_connected_site_tag_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteConnectedSiteTagRequest, + dict, +]) +def test_delete_connected_site_tag(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connected_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteConnectedSiteTagRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_connected_site_tag_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_connected_site_tag), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_connected_site_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConnectedSiteTagRequest() + + +def test_delete_connected_site_tag_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteConnectedSiteTagRequest( + property='property_value', + tag_id='tag_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_connected_site_tag), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_connected_site_tag(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConnectedSiteTagRequest( + property='property_value', + tag_id='tag_id_value', + ) + +def test_delete_connected_site_tag_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_connected_site_tag in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_connected_site_tag] = mock_rpc + request = {} + client.delete_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_connected_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_connected_site_tag_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 = AnalyticsAdminServiceAsyncClient( + 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_connected_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_connected_site_tag() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConnectedSiteTagRequest() + +@pytest.mark.asyncio +async def test_delete_connected_site_tag_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_connected_site_tag in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_connected_site_tag] = mock_object + + request = {} + await client.delete_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_connected_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_connected_site_tag_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteConnectedSiteTagRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connected_site_tag), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteConnectedSiteTagRequest() + 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_connected_site_tag_async_from_dict(): + await test_delete_connected_site_tag_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListConnectedSiteTagsRequest, + dict, +]) +def test_list_connected_site_tags(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connected_site_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListConnectedSiteTagsResponse( + ) + response = client.list_connected_site_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListConnectedSiteTagsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ListConnectedSiteTagsResponse) + + +def test_list_connected_site_tags_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_connected_site_tags), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_connected_site_tags() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListConnectedSiteTagsRequest() + + +def test_list_connected_site_tags_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListConnectedSiteTagsRequest( + property='property_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_connected_site_tags), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_connected_site_tags(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListConnectedSiteTagsRequest( + property='property_value', + ) + +def test_list_connected_site_tags_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_connected_site_tags in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_connected_site_tags] = mock_rpc + request = {} + client.list_connected_site_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_connected_site_tags(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_connected_site_tags_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 = AnalyticsAdminServiceAsyncClient( + 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_connected_site_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConnectedSiteTagsResponse( + )) + response = await client.list_connected_site_tags() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListConnectedSiteTagsRequest() + +@pytest.mark.asyncio +async def test_list_connected_site_tags_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_connected_site_tags in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_connected_site_tags] = mock_object + + request = {} + await client.list_connected_site_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_connected_site_tags(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_connected_site_tags_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListConnectedSiteTagsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_connected_site_tags), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConnectedSiteTagsResponse( + )) + response = await client.list_connected_site_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListConnectedSiteTagsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ListConnectedSiteTagsResponse) + + +@pytest.mark.asyncio +async def test_list_connected_site_tags_async_from_dict(): + await test_list_connected_site_tags_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.FetchConnectedGa4PropertyRequest, + dict, +]) +def test_fetch_connected_ga4_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_connected_ga4_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.FetchConnectedGa4PropertyResponse( + property='property_value', + ) + response = client.fetch_connected_ga4_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.FetchConnectedGa4PropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.FetchConnectedGa4PropertyResponse) + assert response.property == 'property_value' + + +def test_fetch_connected_ga4_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_connected_ga4_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.fetch_connected_ga4_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.FetchConnectedGa4PropertyRequest() + + +def test_fetch_connected_ga4_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.FetchConnectedGa4PropertyRequest( + property='property_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_connected_ga4_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.fetch_connected_ga4_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.FetchConnectedGa4PropertyRequest( + property='property_value', + ) + +def test_fetch_connected_ga4_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.fetch_connected_ga4_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.fetch_connected_ga4_property] = mock_rpc + request = {} + client.fetch_connected_ga4_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_connected_ga4_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_connected_ga4_property_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 = AnalyticsAdminServiceAsyncClient( + 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.fetch_connected_ga4_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.FetchConnectedGa4PropertyResponse( + property='property_value', + )) + response = await client.fetch_connected_ga4_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.FetchConnectedGa4PropertyRequest() + +@pytest.mark.asyncio +async def test_fetch_connected_ga4_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.fetch_connected_ga4_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.fetch_connected_ga4_property] = mock_object + + request = {} + await client.fetch_connected_ga4_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.fetch_connected_ga4_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_fetch_connected_ga4_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.FetchConnectedGa4PropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_connected_ga4_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.FetchConnectedGa4PropertyResponse( + property='property_value', + )) + response = await client.fetch_connected_ga4_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.FetchConnectedGa4PropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.FetchConnectedGa4PropertyResponse) + assert response.property == 'property_value' + + +@pytest.mark.asyncio +async def test_fetch_connected_ga4_property_async_from_dict(): + await test_fetch_connected_ga4_property_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAdSenseLinkRequest, + dict, +]) +def test_get_ad_sense_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdSenseLink( + name='name_value', + ad_client_code='ad_client_code_value', + ) + response = client.get_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAdSenseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdSenseLink) + assert response.name == 'name_value' + assert response.ad_client_code == 'ad_client_code_value' + + +def test_get_ad_sense_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_ad_sense_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_ad_sense_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAdSenseLinkRequest() + + +def test_get_ad_sense_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetAdSenseLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ad_sense_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_ad_sense_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAdSenseLinkRequest( + name='name_value', + ) + +def test_get_ad_sense_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_ad_sense_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_ad_sense_link] = mock_rpc + request = {} + client.get_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_ad_sense_link_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 = AnalyticsAdminServiceAsyncClient( + 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_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AdSenseLink( + name='name_value', + ad_client_code='ad_client_code_value', + )) + response = await client.get_ad_sense_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAdSenseLinkRequest() + +@pytest.mark.asyncio +async def test_get_ad_sense_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_ad_sense_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_ad_sense_link] = mock_object + + request = {} + await client.get_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_ad_sense_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetAdSenseLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.AdSenseLink( + name='name_value', + ad_client_code='ad_client_code_value', + )) + response = await client.get_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAdSenseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdSenseLink) + assert response.name == 'name_value' + assert response.ad_client_code == 'ad_client_code_value' + + +@pytest.mark.asyncio +async def test_get_ad_sense_link_async_from_dict(): + await test_get_ad_sense_link_async(request_type=dict) + + +def test_get_ad_sense_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAdSenseLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ad_sense_link), + '__call__') as call: + call.return_value = resources.AdSenseLink() + client.get_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ad_sense_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAdSenseLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ad_sense_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AdSenseLink()) + await client.get_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ad_sense_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdSenseLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_ad_sense_link( + 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_ad_sense_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_ad_sense_link( + analytics_admin.GetAdSenseLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_ad_sense_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdSenseLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AdSenseLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_ad_sense_link( + 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_ad_sense_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_ad_sense_link( + analytics_admin.GetAdSenseLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateAdSenseLinkRequest, + dict, +]) +def test_create_ad_sense_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdSenseLink( + name='name_value', + ad_client_code='ad_client_code_value', + ) + response = client.create_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateAdSenseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdSenseLink) + assert response.name == 'name_value' + assert response.ad_client_code == 'ad_client_code_value' + + +def test_create_ad_sense_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_ad_sense_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_ad_sense_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateAdSenseLinkRequest() + + +def test_create_ad_sense_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateAdSenseLinkRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ad_sense_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_ad_sense_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateAdSenseLinkRequest( + parent='parent_value', + ) + +def test_create_ad_sense_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_ad_sense_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_ad_sense_link] = mock_rpc + request = {} + client.create_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_ad_sense_link_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 = AnalyticsAdminServiceAsyncClient( + 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_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AdSenseLink( + name='name_value', + ad_client_code='ad_client_code_value', + )) + response = await client.create_ad_sense_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateAdSenseLinkRequest() + +@pytest.mark.asyncio +async def test_create_ad_sense_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_ad_sense_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_ad_sense_link] = mock_object + + request = {} + await client.create_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_ad_sense_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateAdSenseLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.AdSenseLink( + name='name_value', + ad_client_code='ad_client_code_value', + )) + response = await client.create_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateAdSenseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdSenseLink) + assert response.name == 'name_value' + assert response.ad_client_code == 'ad_client_code_value' + + +@pytest.mark.asyncio +async def test_create_ad_sense_link_async_from_dict(): + await test_create_ad_sense_link_async(request_type=dict) + + +def test_create_ad_sense_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateAdSenseLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ad_sense_link), + '__call__') as call: + call.return_value = resources.AdSenseLink() + client.create_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ad_sense_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateAdSenseLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ad_sense_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AdSenseLink()) + await client.create_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ad_sense_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdSenseLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_ad_sense_link( + parent='parent_value', + adsense_link=resources.AdSenseLink(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].adsense_link + mock_val = resources.AdSenseLink(name='name_value') + assert arg == mock_val + + +def test_create_ad_sense_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_ad_sense_link( + analytics_admin.CreateAdSenseLinkRequest(), + parent='parent_value', + adsense_link=resources.AdSenseLink(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_ad_sense_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.AdSenseLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.AdSenseLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_ad_sense_link( + parent='parent_value', + adsense_link=resources.AdSenseLink(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].adsense_link + mock_val = resources.AdSenseLink(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_ad_sense_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_ad_sense_link( + analytics_admin.CreateAdSenseLinkRequest(), + parent='parent_value', + adsense_link=resources.AdSenseLink(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteAdSenseLinkRequest, + dict, +]) +def test_delete_ad_sense_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteAdSenseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_ad_sense_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_ad_sense_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_ad_sense_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAdSenseLinkRequest() + + +def test_delete_ad_sense_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteAdSenseLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_ad_sense_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_ad_sense_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAdSenseLinkRequest( + name='name_value', + ) + +def test_delete_ad_sense_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_ad_sense_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_ad_sense_link] = mock_rpc + request = {} + client.delete_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_ad_sense_link_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 = AnalyticsAdminServiceAsyncClient( + 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_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_ad_sense_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAdSenseLinkRequest() + +@pytest.mark.asyncio +async def test_delete_ad_sense_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_ad_sense_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_ad_sense_link] = mock_object + + request = {} + await client.delete_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_ad_sense_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteAdSenseLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ad_sense_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteAdSenseLinkRequest() + 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_ad_sense_link_async_from_dict(): + await test_delete_ad_sense_link_async(request_type=dict) + + +def test_delete_ad_sense_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteAdSenseLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_ad_sense_link), + '__call__') as call: + call.return_value = None + client.delete_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ad_sense_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteAdSenseLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_ad_sense_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ad_sense_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_ad_sense_link), + '__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_ad_sense_link( + 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_ad_sense_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_ad_sense_link( + analytics_admin.DeleteAdSenseLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_ad_sense_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_ad_sense_link), + '__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_ad_sense_link( + 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_ad_sense_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_ad_sense_link( + analytics_admin.DeleteAdSenseLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAdSenseLinksRequest, + dict, +]) +def test_list_ad_sense_links(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ad_sense_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAdSenseLinksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_ad_sense_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAdSenseLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAdSenseLinksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_ad_sense_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_ad_sense_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_ad_sense_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAdSenseLinksRequest() + + +def test_list_ad_sense_links_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAdSenseLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ad_sense_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_ad_sense_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAdSenseLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_ad_sense_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_ad_sense_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_ad_sense_links] = mock_rpc + request = {} + client.list_ad_sense_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_ad_sense_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_ad_sense_links_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 = AnalyticsAdminServiceAsyncClient( + 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_ad_sense_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAdSenseLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_ad_sense_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAdSenseLinksRequest() + +@pytest.mark.asyncio +async def test_list_ad_sense_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_ad_sense_links in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_ad_sense_links] = mock_object + + request = {} + await client.list_ad_sense_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_ad_sense_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_ad_sense_links_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListAdSenseLinksRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ad_sense_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAdSenseLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_ad_sense_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAdSenseLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAdSenseLinksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_ad_sense_links_async_from_dict(): + await test_list_ad_sense_links_async(request_type=dict) + + +def test_list_ad_sense_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListAdSenseLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ad_sense_links), + '__call__') as call: + call.return_value = analytics_admin.ListAdSenseLinksResponse() + client.list_ad_sense_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ad_sense_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListAdSenseLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ad_sense_links), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAdSenseLinksResponse()) + await client.list_ad_sense_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ad_sense_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ad_sense_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAdSenseLinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_ad_sense_links( + 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_ad_sense_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_ad_sense_links( + analytics_admin.ListAdSenseLinksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_ad_sense_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ad_sense_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAdSenseLinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAdSenseLinksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_ad_sense_links( + 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_ad_sense_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_ad_sense_links( + analytics_admin.ListAdSenseLinksRequest(), + parent='parent_value', + ) + + +def test_list_ad_sense_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_ad_sense_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token='def', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_ad_sense_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AdSenseLink) + for i in results) +def test_list_ad_sense_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_ad_sense_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token='def', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_ad_sense_links(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_ad_sense_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ad_sense_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token='def', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_ad_sense_links(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, resources.AdSenseLink) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_ad_sense_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ad_sense_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token='def', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + 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_ad_sense_links(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", [ + analytics_admin.GetEventCreateRuleRequest, + dict, +]) +def test_get_event_create_rule(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=True, + ) + response = client.get_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == 'name_value' + assert response.destination_event == 'destination_event_value' + assert response.source_copy_parameters is True + + +def test_get_event_create_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEventCreateRuleRequest() + + +def test_get_event_create_rule_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetEventCreateRuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event_create_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEventCreateRuleRequest( + name='name_value', + ) + +def test_get_event_create_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event_create_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event_create_rule] = mock_rpc + request = {} + client.get_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_create_rule_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=True, + )) + response = await client.get_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEventCreateRuleRequest() + +@pytest.mark.asyncio +async def test_get_event_create_rule_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_event_create_rule in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_event_create_rule] = mock_object + + request = {} + await client.get_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_create_rule_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetEventCreateRuleRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=True, + )) + response = await client.get_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == 'name_value' + assert response.destination_event == 'destination_event_value' + assert response.source_copy_parameters is True + + +@pytest.mark.asyncio +async def test_get_event_create_rule_async_from_dict(): + await test_get_event_create_rule_async(request_type=dict) + + +def test_get_event_create_rule_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetEventCreateRuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), + '__call__') as call: + call.return_value = event_create_and_edit.EventCreateRule() + client.get_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_event_create_rule_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetEventCreateRuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule()) + await client.get_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_event_create_rule_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_event_create_rule( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_event_create_rule_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_event_create_rule( + analytics_admin.GetEventCreateRuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_event_create_rule_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_event_create_rule( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_event_create_rule_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_event_create_rule( + analytics_admin.GetEventCreateRuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListEventCreateRulesRequest, + dict, +]) +def test_list_event_create_rules(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_create_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListEventCreateRulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_event_create_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListEventCreateRulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventCreateRulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_event_create_rules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_event_create_rules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_event_create_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListEventCreateRulesRequest() + + +def test_list_event_create_rules_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListEventCreateRulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_create_rules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_event_create_rules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListEventCreateRulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_event_create_rules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_event_create_rules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_event_create_rules] = mock_rpc + request = {} + client.list_event_create_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_event_create_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_event_create_rules_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 = AnalyticsAdminServiceAsyncClient( + 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_event_create_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListEventCreateRulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_event_create_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListEventCreateRulesRequest() + +@pytest.mark.asyncio +async def test_list_event_create_rules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_event_create_rules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_event_create_rules] = mock_object + + request = {} + await client.list_event_create_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_event_create_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_event_create_rules_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListEventCreateRulesRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_create_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListEventCreateRulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_event_create_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListEventCreateRulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventCreateRulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_event_create_rules_async_from_dict(): + await test_list_event_create_rules_async(request_type=dict) + + +def test_list_event_create_rules_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListEventCreateRulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_create_rules), + '__call__') as call: + call.return_value = analytics_admin.ListEventCreateRulesResponse() + client.list_event_create_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_event_create_rules_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListEventCreateRulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_create_rules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListEventCreateRulesResponse()) + await client.list_event_create_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_event_create_rules_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_create_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListEventCreateRulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_event_create_rules( + 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_event_create_rules_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_event_create_rules( + analytics_admin.ListEventCreateRulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_event_create_rules_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_create_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListEventCreateRulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListEventCreateRulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_event_create_rules( + 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_event_create_rules_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_event_create_rules( + analytics_admin.ListEventCreateRulesRequest(), + parent='parent_value', + ) + + +def test_list_event_create_rules_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_event_create_rules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_event_create_rules(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, event_create_and_edit.EventCreateRule) + for i in results) +def test_list_event_create_rules_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_event_create_rules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_event_create_rules(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_event_create_rules_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_create_rules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_event_create_rules(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, event_create_and_edit.EventCreateRule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_event_create_rules_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_create_rules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + 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_event_create_rules(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", [ + analytics_admin.CreateEventCreateRuleRequest, + dict, +]) +def test_create_event_create_rule(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=True, + ) + response = client.create_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == 'name_value' + assert response.destination_event == 'destination_event_value' + assert response.source_copy_parameters is True + + +def test_create_event_create_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateEventCreateRuleRequest() + + +def test_create_event_create_rule_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateEventCreateRuleRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event_create_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateEventCreateRuleRequest( + parent='parent_value', + ) + +def test_create_event_create_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_event_create_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_event_create_rule] = mock_rpc + request = {} + client.create_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_create_rule_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=True, + )) + response = await client.create_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateEventCreateRuleRequest() + +@pytest.mark.asyncio +async def test_create_event_create_rule_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_event_create_rule in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_event_create_rule] = mock_object + + request = {} + await client.create_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_create_rule_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateEventCreateRuleRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=True, + )) + response = await client.create_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == 'name_value' + assert response.destination_event == 'destination_event_value' + assert response.source_copy_parameters is True + + +@pytest.mark.asyncio +async def test_create_event_create_rule_async_from_dict(): + await test_create_event_create_rule_async(request_type=dict) + + +def test_create_event_create_rule_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateEventCreateRuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), + '__call__') as call: + call.return_value = event_create_and_edit.EventCreateRule() + client.create_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_event_create_rule_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateEventCreateRuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule()) + await client.create_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_event_create_rule_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_event_create_rule( + parent='parent_value', + event_create_rule=event_create_and_edit.EventCreateRule(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].event_create_rule + mock_val = event_create_and_edit.EventCreateRule(name='name_value') + assert arg == mock_val + + +def test_create_event_create_rule_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_event_create_rule( + analytics_admin.CreateEventCreateRuleRequest(), + parent='parent_value', + event_create_rule=event_create_and_edit.EventCreateRule(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_event_create_rule_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_event_create_rule( + parent='parent_value', + event_create_rule=event_create_and_edit.EventCreateRule(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].event_create_rule + mock_val = event_create_and_edit.EventCreateRule(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_event_create_rule_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_event_create_rule( + analytics_admin.CreateEventCreateRuleRequest(), + parent='parent_value', + event_create_rule=event_create_and_edit.EventCreateRule(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateEventCreateRuleRequest, + dict, +]) +def test_update_event_create_rule(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=True, + ) + response = client.update_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == 'name_value' + assert response.destination_event == 'destination_event_value' + assert response.source_copy_parameters is True + + +def test_update_event_create_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateEventCreateRuleRequest() + + +def test_update_event_create_rule_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateEventCreateRuleRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event_create_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateEventCreateRuleRequest( + ) + +def test_update_event_create_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_event_create_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event_create_rule] = mock_rpc + request = {} + client.update_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_create_rule_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=True, + )) + response = await client.update_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateEventCreateRuleRequest() + +@pytest.mark.asyncio +async def test_update_event_create_rule_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_event_create_rule in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_event_create_rule] = mock_object + + request = {} + await client.update_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_create_rule_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateEventCreateRuleRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=True, + )) + response = await client.update_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == 'name_value' + assert response.destination_event == 'destination_event_value' + assert response.source_copy_parameters is True + + +@pytest.mark.asyncio +async def test_update_event_create_rule_async_from_dict(): + await test_update_event_create_rule_async(request_type=dict) + + +def test_update_event_create_rule_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateEventCreateRuleRequest() + + request.event_create_rule.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), + '__call__') as call: + call.return_value = event_create_and_edit.EventCreateRule() + client.update_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'event_create_rule.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_event_create_rule_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateEventCreateRuleRequest() + + request.event_create_rule.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule()) + await client.update_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'event_create_rule.name=name_value', + ) in kw['metadata'] + + +def test_update_event_create_rule_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_event_create_rule( + event_create_rule=event_create_and_edit.EventCreateRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].event_create_rule + mock_val = event_create_and_edit.EventCreateRule(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_event_create_rule_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_event_create_rule( + analytics_admin.UpdateEventCreateRuleRequest(), + event_create_rule=event_create_and_edit.EventCreateRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_event_create_rule_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventCreateRule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventCreateRule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_event_create_rule( + event_create_rule=event_create_and_edit.EventCreateRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].event_create_rule + mock_val = event_create_and_edit.EventCreateRule(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_event_create_rule_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_event_create_rule( + analytics_admin.UpdateEventCreateRuleRequest(), + event_create_rule=event_create_and_edit.EventCreateRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteEventCreateRuleRequest, + dict, +]) +def test_delete_event_create_rule(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteEventCreateRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_event_create_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteEventCreateRuleRequest() + + +def test_delete_event_create_rule_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteEventCreateRuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event_create_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteEventCreateRuleRequest( + name='name_value', + ) + +def test_delete_event_create_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_event_create_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_event_create_rule] = mock_rpc + request = {} + client.delete_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_create_rule_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_create_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteEventCreateRuleRequest() + +@pytest.mark.asyncio +async def test_delete_event_create_rule_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_event_create_rule in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_event_create_rule] = mock_object + + request = {} + await client.delete_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_create_rule_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteEventCreateRuleRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteEventCreateRuleRequest() + 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_event_create_rule_async_from_dict(): + await test_delete_event_create_rule_async(request_type=dict) + + +def test_delete_event_create_rule_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteEventCreateRuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), + '__call__') as call: + call.return_value = None + client.delete_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_event_create_rule_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteEventCreateRuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_event_create_rule_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), + '__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_event_create_rule( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_event_create_rule_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_event_create_rule( + analytics_admin.DeleteEventCreateRuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_event_create_rule_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_create_rule), + '__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_event_create_rule( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_event_create_rule_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_event_create_rule( + analytics_admin.DeleteEventCreateRuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetEventEditRuleRequest, + dict, +]) +def test_get_event_edit_rule(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + ) + response = client.get_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetEventEditRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.processing_order == 1720 + + +def test_get_event_edit_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_edit_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event_edit_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEventEditRuleRequest() + + +def test_get_event_edit_rule_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetEventEditRuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_edit_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_event_edit_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEventEditRuleRequest( + name='name_value', + ) + +def test_get_event_edit_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event_edit_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event_edit_rule] = mock_rpc + request = {} + client.get_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_edit_rule_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + )) + response = await client.get_event_edit_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetEventEditRuleRequest() + +@pytest.mark.asyncio +async def test_get_event_edit_rule_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_event_edit_rule in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_event_edit_rule] = mock_object + + request = {} + await client.get_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_event_edit_rule_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetEventEditRuleRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + )) + response = await client.get_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetEventEditRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.processing_order == 1720 + + +@pytest.mark.asyncio +async def test_get_event_edit_rule_async_from_dict(): + await test_get_event_edit_rule_async(request_type=dict) + + +def test_get_event_edit_rule_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetEventEditRuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_edit_rule), + '__call__') as call: + call.return_value = event_create_and_edit.EventEditRule() + client.get_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_event_edit_rule_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetEventEditRuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_edit_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule()) + await client.get_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_event_edit_rule_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventEditRule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_event_edit_rule( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_event_edit_rule_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_event_edit_rule( + analytics_admin.GetEventEditRuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_event_edit_rule_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventEditRule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_event_edit_rule( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_event_edit_rule_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_event_edit_rule( + analytics_admin.GetEventEditRuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListEventEditRulesRequest, + dict, +]) +def test_list_event_edit_rules(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_edit_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListEventEditRulesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListEventEditRulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventEditRulesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_event_edit_rules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_event_edit_rules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_event_edit_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListEventEditRulesRequest() + + +def test_list_event_edit_rules_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListEventEditRulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_event_edit_rules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListEventEditRulesRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_event_edit_rules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_event_edit_rules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_event_edit_rules] = mock_rpc + request = {} + client.list_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_event_edit_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_event_edit_rules_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 = AnalyticsAdminServiceAsyncClient( + 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_event_edit_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListEventEditRulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_event_edit_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListEventEditRulesRequest() + +@pytest.mark.asyncio +async def test_list_event_edit_rules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_event_edit_rules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_event_edit_rules] = mock_object + + request = {} + await client.list_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_event_edit_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_event_edit_rules_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListEventEditRulesRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_event_edit_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListEventEditRulesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListEventEditRulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventEditRulesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_event_edit_rules_async_from_dict(): + await test_list_event_edit_rules_async(request_type=dict) + + +def test_list_event_edit_rules_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListEventEditRulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), + '__call__') as call: + call.return_value = analytics_admin.ListEventEditRulesResponse() + client.list_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_event_edit_rules_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListEventEditRulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListEventEditRulesResponse()) + await client.list_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_event_edit_rules_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListEventEditRulesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_event_edit_rules( + 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_event_edit_rules_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_event_edit_rules( + analytics_admin.ListEventEditRulesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_event_edit_rules_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListEventEditRulesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListEventEditRulesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_event_edit_rules( + 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_event_edit_rules_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_event_edit_rules( + analytics_admin.ListEventEditRulesRequest(), + parent='parent_value', + ) + + +def test_list_event_edit_rules_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_event_edit_rules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_event_edit_rules(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, event_create_and_edit.EventEditRule) + for i in results) +def test_list_event_edit_rules_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_event_edit_rules), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + ), + RuntimeError, + ) + pages = list(client.list_event_edit_rules(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_event_edit_rules_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_event_edit_rules(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, event_create_and_edit.EventEditRule) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_event_edit_rules_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_event_edit_rules), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + ), + 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_event_edit_rules(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", [ + analytics_admin.CreateEventEditRuleRequest, + dict, +]) +def test_create_event_edit_rule(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + ) + response = client.create_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateEventEditRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.processing_order == 1720 + + +def test_create_event_edit_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_edit_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event_edit_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateEventEditRuleRequest() + + +def test_create_event_edit_rule_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateEventEditRuleRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_edit_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_event_edit_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateEventEditRuleRequest( + parent='parent_value', + ) + +def test_create_event_edit_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_event_edit_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_event_edit_rule] = mock_rpc + request = {} + client.create_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_edit_rule_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + )) + response = await client.create_event_edit_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateEventEditRuleRequest() + +@pytest.mark.asyncio +async def test_create_event_edit_rule_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_event_edit_rule in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_event_edit_rule] = mock_object + + request = {} + await client.create_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_event_edit_rule_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateEventEditRuleRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + )) + response = await client.create_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateEventEditRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.processing_order == 1720 + + +@pytest.mark.asyncio +async def test_create_event_edit_rule_async_from_dict(): + await test_create_event_edit_rule_async(request_type=dict) + + +def test_create_event_edit_rule_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateEventEditRuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_edit_rule), + '__call__') as call: + call.return_value = event_create_and_edit.EventEditRule() + client.create_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_event_edit_rule_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateEventEditRuleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_edit_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule()) + await client.create_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_event_edit_rule_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventEditRule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_event_edit_rule( + parent='parent_value', + event_edit_rule=event_create_and_edit.EventEditRule(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].event_edit_rule + mock_val = event_create_and_edit.EventEditRule(name='name_value') + assert arg == mock_val + + +def test_create_event_edit_rule_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_event_edit_rule( + analytics_admin.CreateEventEditRuleRequest(), + parent='parent_value', + event_edit_rule=event_create_and_edit.EventEditRule(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_event_edit_rule_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventEditRule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_event_edit_rule( + parent='parent_value', + event_edit_rule=event_create_and_edit.EventEditRule(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].event_edit_rule + mock_val = event_create_and_edit.EventEditRule(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_event_edit_rule_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_event_edit_rule( + analytics_admin.CreateEventEditRuleRequest(), + parent='parent_value', + event_edit_rule=event_create_and_edit.EventEditRule(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateEventEditRuleRequest, + dict, +]) +def test_update_event_edit_rule(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + ) + response = client.update_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateEventEditRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.processing_order == 1720 + + +def test_update_event_edit_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_edit_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event_edit_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateEventEditRuleRequest() + + +def test_update_event_edit_rule_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateEventEditRuleRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_edit_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_event_edit_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateEventEditRuleRequest( + ) + +def test_update_event_edit_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_event_edit_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event_edit_rule] = mock_rpc + request = {} + client.update_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_edit_rule_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + )) + response = await client.update_event_edit_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateEventEditRuleRequest() + +@pytest.mark.asyncio +async def test_update_event_edit_rule_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_event_edit_rule in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_event_edit_rule] = mock_object + + request = {} + await client.update_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_event_edit_rule_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateEventEditRuleRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + )) + response = await client.update_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateEventEditRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.processing_order == 1720 + + +@pytest.mark.asyncio +async def test_update_event_edit_rule_async_from_dict(): + await test_update_event_edit_rule_async(request_type=dict) + + +def test_update_event_edit_rule_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateEventEditRuleRequest() + + request.event_edit_rule.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_edit_rule), + '__call__') as call: + call.return_value = event_create_and_edit.EventEditRule() + client.update_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'event_edit_rule.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_event_edit_rule_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateEventEditRuleRequest() + + request.event_edit_rule.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_edit_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule()) + await client.update_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'event_edit_rule.name=name_value', + ) in kw['metadata'] + + +def test_update_event_edit_rule_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventEditRule() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_event_edit_rule( + event_edit_rule=event_create_and_edit.EventEditRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].event_edit_rule + mock_val = event_create_and_edit.EventEditRule(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_event_edit_rule_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_event_edit_rule( + analytics_admin.UpdateEventEditRuleRequest(), + event_edit_rule=event_create_and_edit.EventEditRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_event_edit_rule_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = event_create_and_edit.EventEditRule() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(event_create_and_edit.EventEditRule()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_event_edit_rule( + event_edit_rule=event_create_and_edit.EventEditRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].event_edit_rule + mock_val = event_create_and_edit.EventEditRule(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_event_edit_rule_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_event_edit_rule( + analytics_admin.UpdateEventEditRuleRequest(), + event_edit_rule=event_create_and_edit.EventEditRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteEventEditRuleRequest, + dict, +]) +def test_delete_event_edit_rule(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteEventEditRuleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_event_edit_rule_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_edit_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event_edit_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteEventEditRuleRequest() + + +def test_delete_event_edit_rule_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteEventEditRuleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_edit_rule), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_event_edit_rule(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteEventEditRuleRequest( + name='name_value', + ) + +def test_delete_event_edit_rule_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_event_edit_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_event_edit_rule] = mock_rpc + request = {} + client.delete_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_edit_rule_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_edit_rule() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteEventEditRuleRequest() + +@pytest.mark.asyncio +async def test_delete_event_edit_rule_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_event_edit_rule in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_event_edit_rule] = mock_object + + request = {} + await client.delete_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_event_edit_rule_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteEventEditRuleRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_edit_rule), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteEventEditRuleRequest() + 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_event_edit_rule_async_from_dict(): + await test_delete_event_edit_rule_async(request_type=dict) + + +def test_delete_event_edit_rule_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteEventEditRuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_edit_rule), + '__call__') as call: + call.return_value = None + client.delete_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_event_edit_rule_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteEventEditRuleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_edit_rule), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_event_edit_rule_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_edit_rule), + '__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_event_edit_rule( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_event_edit_rule_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_event_edit_rule( + analytics_admin.DeleteEventEditRuleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_event_edit_rule_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_event_edit_rule), + '__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_event_edit_rule( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_event_edit_rule_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_event_edit_rule( + analytics_admin.DeleteEventEditRuleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ReorderEventEditRulesRequest, + dict, +]) +def test_reorder_event_edit_rules(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reorder_event_edit_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.reorder_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ReorderEventEditRulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_reorder_event_edit_rules_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reorder_event_edit_rules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.reorder_event_edit_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ReorderEventEditRulesRequest() + + +def test_reorder_event_edit_rules_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ReorderEventEditRulesRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reorder_event_edit_rules), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.reorder_event_edit_rules(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ReorderEventEditRulesRequest( + parent='parent_value', + ) + +def test_reorder_event_edit_rules_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.reorder_event_edit_rules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.reorder_event_edit_rules] = mock_rpc + request = {} + client.reorder_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.reorder_event_edit_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_reorder_event_edit_rules_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 = AnalyticsAdminServiceAsyncClient( + 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.reorder_event_edit_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.reorder_event_edit_rules() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ReorderEventEditRulesRequest() + +@pytest.mark.asyncio +async def test_reorder_event_edit_rules_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.reorder_event_edit_rules in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.reorder_event_edit_rules] = mock_object + + request = {} + await client.reorder_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.reorder_event_edit_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_reorder_event_edit_rules_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ReorderEventEditRulesRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reorder_event_edit_rules), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.reorder_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ReorderEventEditRulesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_reorder_event_edit_rules_async_from_dict(): + await test_reorder_event_edit_rules_async(request_type=dict) + + +def test_reorder_event_edit_rules_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ReorderEventEditRulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reorder_event_edit_rules), + '__call__') as call: + call.return_value = None + client.reorder_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_reorder_event_edit_rules_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ReorderEventEditRulesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reorder_event_edit_rules), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.reorder_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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", [ + analytics_admin.UpdateDataRedactionSettingsRequest, + dict, +]) +def test_update_data_redaction_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRedactionSettings( + name='name_value', + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=['query_parameter_keys_value'], + ) + response = client.update_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataRedactionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRedactionSettings) + assert response.name == 'name_value' + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ['query_parameter_keys_value'] + + +def test_update_data_redaction_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_redaction_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_redaction_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataRedactionSettingsRequest() + + +def test_update_data_redaction_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateDataRedactionSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_redaction_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_redaction_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataRedactionSettingsRequest( + ) + +def test_update_data_redaction_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_redaction_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_redaction_settings] = mock_rpc + request = {} + client.update_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_redaction_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_redaction_settings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRedactionSettings( + name='name_value', + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=['query_parameter_keys_value'], + )) + response = await client.update_data_redaction_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataRedactionSettingsRequest() + +@pytest.mark.asyncio +async def test_update_data_redaction_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_data_redaction_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_data_redaction_settings] = mock_object + + request = {} + await client.update_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_data_redaction_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_redaction_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateDataRedactionSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRedactionSettings( + name='name_value', + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=['query_parameter_keys_value'], + )) + response = await client.update_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataRedactionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRedactionSettings) + assert response.name == 'name_value' + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ['query_parameter_keys_value'] + + +@pytest.mark.asyncio +async def test_update_data_redaction_settings_async_from_dict(): + await test_update_data_redaction_settings_async(request_type=dict) + + +def test_update_data_redaction_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataRedactionSettingsRequest() + + request.data_redaction_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_redaction_settings), + '__call__') as call: + call.return_value = resources.DataRedactionSettings() + client.update_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_redaction_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_data_redaction_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataRedactionSettingsRequest() + + request.data_redaction_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_redaction_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRedactionSettings()) + await client.update_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_redaction_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_data_redaction_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRedactionSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_redaction_settings( + data_redaction_settings=resources.DataRedactionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].data_redaction_settings + mock_val = resources.DataRedactionSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_data_redaction_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_redaction_settings( + analytics_admin.UpdateDataRedactionSettingsRequest(), + data_redaction_settings=resources.DataRedactionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_data_redaction_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRedactionSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRedactionSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_redaction_settings( + data_redaction_settings=resources.DataRedactionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].data_redaction_settings + mock_val = resources.DataRedactionSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_data_redaction_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_data_redaction_settings( + analytics_admin.UpdateDataRedactionSettingsRequest(), + data_redaction_settings=resources.DataRedactionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataRedactionSettingsRequest, + dict, +]) +def test_get_data_redaction_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRedactionSettings( + name='name_value', + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=['query_parameter_keys_value'], + ) + response = client.get_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataRedactionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRedactionSettings) + assert response.name == 'name_value' + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ['query_parameter_keys_value'] + + +def test_get_data_redaction_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_redaction_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_redaction_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataRedactionSettingsRequest() + + +def test_get_data_redaction_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetDataRedactionSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_redaction_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_redaction_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataRedactionSettingsRequest( + name='name_value', + ) + +def test_get_data_redaction_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_redaction_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_redaction_settings] = mock_rpc + request = {} + client.get_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_redaction_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_redaction_settings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRedactionSettings( + name='name_value', + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=['query_parameter_keys_value'], + )) + response = await client.get_data_redaction_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataRedactionSettingsRequest() + +@pytest.mark.asyncio +async def test_get_data_redaction_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_data_redaction_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_data_redaction_settings] = mock_object + + request = {} + await client.get_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_data_redaction_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_redaction_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetDataRedactionSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRedactionSettings( + name='name_value', + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=['query_parameter_keys_value'], + )) + response = await client.get_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataRedactionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRedactionSettings) + assert response.name == 'name_value' + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ['query_parameter_keys_value'] + + +@pytest.mark.asyncio +async def test_get_data_redaction_settings_async_from_dict(): + await test_get_data_redaction_settings_async(request_type=dict) + + +def test_get_data_redaction_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataRedactionSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_redaction_settings), + '__call__') as call: + call.return_value = resources.DataRedactionSettings() + client.get_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_data_redaction_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataRedactionSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_redaction_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRedactionSettings()) + await client.get_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_data_redaction_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRedactionSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_redaction_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_data_redaction_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_redaction_settings( + analytics_admin.GetDataRedactionSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_redaction_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_redaction_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRedactionSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRedactionSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_redaction_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_data_redaction_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_redaction_settings( + analytics_admin.GetDataRedactionSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCalculatedMetricRequest, + dict, +]) +def test_get_calculated_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=True, + ) + response = client.get_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.display_name == 'display_name_value' + assert response.calculated_metric_id == 'calculated_metric_id_value' + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [resources.CalculatedMetric.RestrictedMetricType.COST_DATA] + assert response.formula == 'formula_value' + assert response.invalid_metric_reference is True + + +def test_get_calculated_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCalculatedMetricRequest() + + +def test_get_calculated_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetCalculatedMetricRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_calculated_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCalculatedMetricRequest( + name='name_value', + ) + +def test_get_calculated_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_calculated_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_calculated_metric] = mock_rpc + request = {} + client.get_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_calculated_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=True, + )) + response = await client.get_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCalculatedMetricRequest() + +@pytest.mark.asyncio +async def test_get_calculated_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_calculated_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_calculated_metric] = mock_object + + request = {} + await client.get_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_calculated_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetCalculatedMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=True, + )) + response = await client.get_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.display_name == 'display_name_value' + assert response.calculated_metric_id == 'calculated_metric_id_value' + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [resources.CalculatedMetric.RestrictedMetricType.COST_DATA] + assert response.formula == 'formula_value' + assert response.invalid_metric_reference is True + + +@pytest.mark.asyncio +async def test_get_calculated_metric_async_from_dict(): + await test_get_calculated_metric_async(request_type=dict) + + +def test_get_calculated_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCalculatedMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), + '__call__') as call: + call.return_value = resources.CalculatedMetric() + client.get_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_calculated_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCalculatedMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric()) + await client.get_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_calculated_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_calculated_metric( + 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_calculated_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metric( + analytics_admin.GetCalculatedMetricRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_calculated_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_calculated_metric( + 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_calculated_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_calculated_metric( + analytics_admin.GetCalculatedMetricRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateCalculatedMetricRequest, + dict, +]) +def test_create_calculated_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=True, + ) + response = client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.display_name == 'display_name_value' + assert response.calculated_metric_id == 'calculated_metric_id_value' + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [resources.CalculatedMetric.RestrictedMetricType.COST_DATA] + assert response.formula == 'formula_value' + assert response.invalid_metric_reference is True + + +def test_create_calculated_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCalculatedMetricRequest() + + +def test_create_calculated_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateCalculatedMetricRequest( + parent='parent_value', + calculated_metric_id='calculated_metric_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_calculated_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCalculatedMetricRequest( + parent='parent_value', + calculated_metric_id='calculated_metric_id_value', + ) + +def test_create_calculated_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_calculated_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_calculated_metric] = mock_rpc + request = {} + client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_calculated_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=True, + )) + response = await client.create_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCalculatedMetricRequest() + +@pytest.mark.asyncio +async def test_create_calculated_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_calculated_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_calculated_metric] = mock_object + + request = {} + await client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_calculated_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateCalculatedMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=True, + )) + response = await client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.display_name == 'display_name_value' + assert response.calculated_metric_id == 'calculated_metric_id_value' + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [resources.CalculatedMetric.RestrictedMetricType.COST_DATA] + assert response.formula == 'formula_value' + assert response.invalid_metric_reference is True + + +@pytest.mark.asyncio +async def test_create_calculated_metric_async_from_dict(): + await test_create_calculated_metric_async(request_type=dict) + + +def test_create_calculated_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCalculatedMetricRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), + '__call__') as call: + call.return_value = resources.CalculatedMetric() + client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_calculated_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCalculatedMetricRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric()) + await client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_calculated_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_calculated_metric( + parent='parent_value', + calculated_metric=resources.CalculatedMetric(name='name_value'), + calculated_metric_id='calculated_metric_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].calculated_metric + mock_val = resources.CalculatedMetric(name='name_value') + assert arg == mock_val + arg = args[0].calculated_metric_id + mock_val = 'calculated_metric_id_value' + assert arg == mock_val + + +def test_create_calculated_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metric( + analytics_admin.CreateCalculatedMetricRequest(), + parent='parent_value', + calculated_metric=resources.CalculatedMetric(name='name_value'), + calculated_metric_id='calculated_metric_id_value', + ) + +@pytest.mark.asyncio +async def test_create_calculated_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_calculated_metric( + parent='parent_value', + calculated_metric=resources.CalculatedMetric(name='name_value'), + calculated_metric_id='calculated_metric_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].calculated_metric + mock_val = resources.CalculatedMetric(name='name_value') + assert arg == mock_val + arg = args[0].calculated_metric_id + mock_val = 'calculated_metric_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_calculated_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_calculated_metric( + analytics_admin.CreateCalculatedMetricRequest(), + parent='parent_value', + calculated_metric=resources.CalculatedMetric(name='name_value'), + calculated_metric_id='calculated_metric_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCalculatedMetricsRequest, + dict, +]) +def test_list_calculated_metrics(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCalculatedMetricsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCalculatedMetricsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCalculatedMetricsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_calculated_metrics_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metrics), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_calculated_metrics() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCalculatedMetricsRequest() + + +def test_list_calculated_metrics_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCalculatedMetricsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_calculated_metrics(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCalculatedMetricsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_calculated_metrics_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_calculated_metrics in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_calculated_metrics] = mock_rpc + request = {} + client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_calculated_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_calculated_metrics_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 = AnalyticsAdminServiceAsyncClient( + 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_calculated_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCalculatedMetricsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_calculated_metrics() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCalculatedMetricsRequest() + +@pytest.mark.asyncio +async def test_list_calculated_metrics_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_calculated_metrics in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_calculated_metrics] = mock_object + + request = {} + await client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_calculated_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_calculated_metrics_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListCalculatedMetricsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCalculatedMetricsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCalculatedMetricsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCalculatedMetricsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_async_from_dict(): + await test_list_calculated_metrics_async(request_type=dict) + + +def test_list_calculated_metrics_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCalculatedMetricsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), + '__call__') as call: + call.return_value = analytics_admin.ListCalculatedMetricsResponse() + client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_calculated_metrics_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCalculatedMetricsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCalculatedMetricsResponse()) + await client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_calculated_metrics_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCalculatedMetricsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_calculated_metrics( + 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_calculated_metrics_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metrics( + analytics_admin.ListCalculatedMetricsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_calculated_metrics_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCalculatedMetricsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCalculatedMetricsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_calculated_metrics( + 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_calculated_metrics_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_calculated_metrics( + analytics_admin.ListCalculatedMetricsRequest(), + parent='parent_value', + ) + + +def test_list_calculated_metrics_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_calculated_metrics), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_calculated_metrics(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CalculatedMetric) + for i in results) +def test_list_calculated_metrics_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_calculated_metrics), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + ), + RuntimeError, + ) + pages = list(client.list_calculated_metrics(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_calculated_metrics_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_calculated_metrics(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, resources.CalculatedMetric) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_calculated_metrics_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_calculated_metrics), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + ), + 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_calculated_metrics(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", [ + analytics_admin.UpdateCalculatedMetricRequest, + dict, +]) +def test_update_calculated_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=True, + ) + response = client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.display_name == 'display_name_value' + assert response.calculated_metric_id == 'calculated_metric_id_value' + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [resources.CalculatedMetric.RestrictedMetricType.COST_DATA] + assert response.formula == 'formula_value' + assert response.invalid_metric_reference is True + + +def test_update_calculated_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCalculatedMetricRequest() + + +def test_update_calculated_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateCalculatedMetricRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_calculated_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCalculatedMetricRequest( + ) + +def test_update_calculated_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_calculated_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_calculated_metric] = mock_rpc + request = {} + client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_calculated_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=True, + )) + response = await client.update_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCalculatedMetricRequest() + +@pytest.mark.asyncio +async def test_update_calculated_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_calculated_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_calculated_metric] = mock_object + + request = {} + await client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_calculated_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateCalculatedMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=True, + )) + response = await client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.display_name == 'display_name_value' + assert response.calculated_metric_id == 'calculated_metric_id_value' + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [resources.CalculatedMetric.RestrictedMetricType.COST_DATA] + assert response.formula == 'formula_value' + assert response.invalid_metric_reference is True + + +@pytest.mark.asyncio +async def test_update_calculated_metric_async_from_dict(): + await test_update_calculated_metric_async(request_type=dict) + + +def test_update_calculated_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCalculatedMetricRequest() + + request.calculated_metric.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), + '__call__') as call: + call.return_value = resources.CalculatedMetric() + client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'calculated_metric.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_calculated_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCalculatedMetricRequest() + + request.calculated_metric.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric()) + await client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'calculated_metric.name=name_value', + ) in kw['metadata'] + + +def test_update_calculated_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_calculated_metric( + calculated_metric=resources.CalculatedMetric(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].calculated_metric + mock_val = resources.CalculatedMetric(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_calculated_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metric( + analytics_admin.UpdateCalculatedMetricRequest(), + calculated_metric=resources.CalculatedMetric(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_calculated_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CalculatedMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CalculatedMetric()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_calculated_metric( + calculated_metric=resources.CalculatedMetric(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].calculated_metric + mock_val = resources.CalculatedMetric(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_calculated_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_calculated_metric( + analytics_admin.UpdateCalculatedMetricRequest(), + calculated_metric=resources.CalculatedMetric(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteCalculatedMetricRequest, + dict, +]) +def test_delete_calculated_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteCalculatedMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_calculated_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteCalculatedMetricRequest() + + +def test_delete_calculated_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteCalculatedMetricRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_calculated_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteCalculatedMetricRequest( + name='name_value', + ) + +def test_delete_calculated_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_calculated_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_calculated_metric] = mock_rpc + request = {} + client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_calculated_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_calculated_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteCalculatedMetricRequest() + +@pytest.mark.asyncio +async def test_delete_calculated_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_calculated_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_calculated_metric] = mock_object + + request = {} + await client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_calculated_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteCalculatedMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_calculated_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteCalculatedMetricRequest() + 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_calculated_metric_async_from_dict(): + await test_delete_calculated_metric_async(request_type=dict) + + +def test_delete_calculated_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteCalculatedMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), + '__call__') as call: + call.return_value = None + client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_calculated_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteCalculatedMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_calculated_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), + '__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_calculated_metric( + 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_calculated_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_calculated_metric( + analytics_admin.DeleteCalculatedMetricRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_calculated_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_calculated_metric), + '__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_calculated_metric( + 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_calculated_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_calculated_metric( + analytics_admin.DeleteCalculatedMetricRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateRollupPropertyRequest, + dict, +]) +def test_create_rollup_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.CreateRollupPropertyResponse( + ) + response = client.create_rollup_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateRollupPropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.CreateRollupPropertyResponse) + + +def test_create_rollup_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_rollup_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_rollup_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertyRequest() + + +def test_create_rollup_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateRollupPropertyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_rollup_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertyRequest( + ) + +def test_create_rollup_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_rollup_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_rollup_property] = mock_rpc + request = {} + client.create_rollup_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_rollup_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_rollup_property_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 = AnalyticsAdminServiceAsyncClient( + 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_rollup_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.CreateRollupPropertyResponse( + )) + response = await client.create_rollup_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertyRequest() + +@pytest.mark.asyncio +async def test_create_rollup_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_rollup_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_rollup_property] = mock_object + + request = {} + await client.create_rollup_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_rollup_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_rollup_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateRollupPropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.CreateRollupPropertyResponse( + )) + response = await client.create_rollup_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateRollupPropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.CreateRollupPropertyResponse) + + +@pytest.mark.asyncio +async def test_create_rollup_property_async_from_dict(): + await test_create_rollup_property_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetRollupPropertySourceLinkRequest, + dict, +]) +def test_get_rollup_property_source_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink( + name='name_value', + source_property='source_property_value', + ) + response = client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == 'name_value' + assert response.source_property == 'source_property_value' + + +def test_get_rollup_property_source_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_rollup_property_source_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetRollupPropertySourceLinkRequest() + + +def test_get_rollup_property_source_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetRollupPropertySourceLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_rollup_property_source_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetRollupPropertySourceLinkRequest( + name='name_value', + ) + +def test_get_rollup_property_source_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_rollup_property_source_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_rollup_property_source_link] = mock_rpc + request = {} + client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_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 = AnalyticsAdminServiceAsyncClient( + 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_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.RollupPropertySourceLink( + name='name_value', + source_property='source_property_value', + )) + response = await client.get_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetRollupPropertySourceLinkRequest() + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_rollup_property_source_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_rollup_property_source_link] = mock_object + + request = {} + await client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetRollupPropertySourceLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.RollupPropertySourceLink( + name='name_value', + source_property='source_property_value', + )) + response = await client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == 'name_value' + assert response.source_property == 'source_property_value' + + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_async_from_dict(): + await test_get_rollup_property_source_link_async(request_type=dict) + + +def test_get_rollup_property_source_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetRollupPropertySourceLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), + '__call__') as call: + call.return_value = resources.RollupPropertySourceLink() + client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_rollup_property_source_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetRollupPropertySourceLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.RollupPropertySourceLink()) + await client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_rollup_property_source_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_rollup_property_source_link( + 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_rollup_property_source_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_rollup_property_source_link( + analytics_admin.GetRollupPropertySourceLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_rollup_property_source_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.RollupPropertySourceLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_rollup_property_source_link( + 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_rollup_property_source_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_rollup_property_source_link( + analytics_admin.GetRollupPropertySourceLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListRollupPropertySourceLinksRequest, + dict, +]) +def test_list_rollup_property_source_links(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property_source_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListRollupPropertySourceLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRollupPropertySourceLinksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_rollup_property_source_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_rollup_property_source_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_rollup_property_source_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListRollupPropertySourceLinksRequest() + + +def test_list_rollup_property_source_links_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListRollupPropertySourceLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_rollup_property_source_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListRollupPropertySourceLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_rollup_property_source_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_rollup_property_source_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_rollup_property_source_links] = mock_rpc + request = {} + client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_rollup_property_source_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_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 = AnalyticsAdminServiceAsyncClient( + 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_rollup_property_source_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListRollupPropertySourceLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_rollup_property_source_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListRollupPropertySourceLinksRequest() + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_rollup_property_source_links in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_rollup_property_source_links] = mock_object + + request = {} + await client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_rollup_property_source_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListRollupPropertySourceLinksRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property_source_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListRollupPropertySourceLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListRollupPropertySourceLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRollupPropertySourceLinksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_async_from_dict(): + await test_list_rollup_property_source_links_async(request_type=dict) + + +def test_list_rollup_property_source_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListRollupPropertySourceLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), + '__call__') as call: + call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_rollup_property_source_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListRollupPropertySourceLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListRollupPropertySourceLinksResponse()) + await client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_rollup_property_source_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_rollup_property_source_links( + 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_rollup_property_source_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_rollup_property_source_links( + analytics_admin.ListRollupPropertySourceLinksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListRollupPropertySourceLinksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_rollup_property_source_links( + 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_rollup_property_source_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_rollup_property_source_links( + analytics_admin.ListRollupPropertySourceLinksRequest(), + parent='parent_value', + ) + + +def test_list_rollup_property_source_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_rollup_property_source_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[], + next_page_token='def', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_rollup_property_source_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.RollupPropertySourceLink) + for i in results) +def test_list_rollup_property_source_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_rollup_property_source_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[], + next_page_token='def', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_rollup_property_source_links(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_rollup_property_source_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[], + next_page_token='def', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_rollup_property_source_links(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, resources.RollupPropertySourceLink) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_rollup_property_source_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_rollup_property_source_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[], + next_page_token='def', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + ), + 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_rollup_property_source_links(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", [ + analytics_admin.CreateRollupPropertySourceLinkRequest, + dict, +]) +def test_create_rollup_property_source_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink( + name='name_value', + source_property='source_property_value', + ) + response = client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == 'name_value' + assert response.source_property == 'source_property_value' + + +def test_create_rollup_property_source_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_rollup_property_source_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertySourceLinkRequest() + + +def test_create_rollup_property_source_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateRollupPropertySourceLinkRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_rollup_property_source_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertySourceLinkRequest( + parent='parent_value', + ) + +def test_create_rollup_property_source_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_rollup_property_source_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_rollup_property_source_link] = mock_rpc + request = {} + client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_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 = AnalyticsAdminServiceAsyncClient( + 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_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.RollupPropertySourceLink( + name='name_value', + source_property='source_property_value', + )) + response = await client.create_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateRollupPropertySourceLinkRequest() + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_rollup_property_source_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_rollup_property_source_link] = mock_object + + request = {} + await client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateRollupPropertySourceLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.RollupPropertySourceLink( + name='name_value', + source_property='source_property_value', + )) + response = await client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == 'name_value' + assert response.source_property == 'source_property_value' + + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_async_from_dict(): + await test_create_rollup_property_source_link_async(request_type=dict) + + +def test_create_rollup_property_source_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateRollupPropertySourceLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), + '__call__') as call: + call.return_value = resources.RollupPropertySourceLink() + client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_rollup_property_source_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateRollupPropertySourceLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.RollupPropertySourceLink()) + await client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_rollup_property_source_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_rollup_property_source_link( + parent='parent_value', + rollup_property_source_link=resources.RollupPropertySourceLink(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].rollup_property_source_link + mock_val = resources.RollupPropertySourceLink(name='name_value') + assert arg == mock_val + + +def test_create_rollup_property_source_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_rollup_property_source_link( + analytics_admin.CreateRollupPropertySourceLinkRequest(), + parent='parent_value', + rollup_property_source_link=resources.RollupPropertySourceLink(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.RollupPropertySourceLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.RollupPropertySourceLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_rollup_property_source_link( + parent='parent_value', + rollup_property_source_link=resources.RollupPropertySourceLink(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].rollup_property_source_link + mock_val = resources.RollupPropertySourceLink(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_rollup_property_source_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_rollup_property_source_link( + analytics_admin.CreateRollupPropertySourceLinkRequest(), + parent='parent_value', + rollup_property_source_link=resources.RollupPropertySourceLink(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteRollupPropertySourceLinkRequest, + dict, +]) +def test_delete_rollup_property_source_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_rollup_property_source_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_rollup_property_source_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteRollupPropertySourceLinkRequest() + + +def test_delete_rollup_property_source_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteRollupPropertySourceLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_rollup_property_source_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteRollupPropertySourceLinkRequest( + name='name_value', + ) + +def test_delete_rollup_property_source_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_rollup_property_source_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_rollup_property_source_link] = mock_rpc + request = {} + client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_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 = AnalyticsAdminServiceAsyncClient( + 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_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_rollup_property_source_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteRollupPropertySourceLinkRequest() + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_rollup_property_source_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_rollup_property_source_link] = mock_object + + request = {} + await client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteRollupPropertySourceLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_rollup_property_source_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + 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_rollup_property_source_link_async_from_dict(): + await test_delete_rollup_property_source_link_async(request_type=dict) + + +def test_delete_rollup_property_source_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), + '__call__') as call: + call.return_value = None + client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_rollup_property_source_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteRollupPropertySourceLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_rollup_property_source_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), + '__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_rollup_property_source_link( + 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_rollup_property_source_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_rollup_property_source_link( + analytics_admin.DeleteRollupPropertySourceLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_rollup_property_source_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_rollup_property_source_link), + '__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_rollup_property_source_link( + 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_rollup_property_source_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_rollup_property_source_link( + analytics_admin.DeleteRollupPropertySourceLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ProvisionSubpropertyRequest, + dict, +]) +def test_provision_subproperty(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_subproperty), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ProvisionSubpropertyResponse( + ) + response = client.provision_subproperty(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ProvisionSubpropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionSubpropertyResponse) + + +def test_provision_subproperty_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_subproperty), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.provision_subproperty() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionSubpropertyRequest() + + +def test_provision_subproperty_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ProvisionSubpropertyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_subproperty), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.provision_subproperty(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionSubpropertyRequest( + ) + +def test_provision_subproperty_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.provision_subproperty in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.provision_subproperty] = mock_rpc + request = {} + client.provision_subproperty(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provision_subproperty(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_provision_subproperty_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 = AnalyticsAdminServiceAsyncClient( + 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.provision_subproperty), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ProvisionSubpropertyResponse( + )) + response = await client.provision_subproperty() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionSubpropertyRequest() + +@pytest.mark.asyncio +async def test_provision_subproperty_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.provision_subproperty in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.provision_subproperty] = mock_object + + request = {} + await client.provision_subproperty(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.provision_subproperty(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_provision_subproperty_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ProvisionSubpropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_subproperty), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ProvisionSubpropertyResponse( + )) + response = await client.provision_subproperty(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ProvisionSubpropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionSubpropertyResponse) + + +@pytest.mark.asyncio +async def test_provision_subproperty_async_from_dict(): + await test_provision_subproperty_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateSubpropertyEventFilterRequest, + dict, +]) +def test_create_subproperty_event_filter(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_value', + ) + response = client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == 'name_value' + assert response.apply_to_property == 'apply_to_property_value' + + +def test_create_subproperty_event_filter_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filter), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSubpropertyEventFilterRequest() + + +def test_create_subproperty_event_filter_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateSubpropertyEventFilterRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_subproperty_event_filter(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSubpropertyEventFilterRequest( + parent='parent_value', + ) + +def test_create_subproperty_event_filter_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_subproperty_event_filter in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_subproperty_event_filter] = mock_rpc + request = {} + client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_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 = AnalyticsAdminServiceAsyncClient( + 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_value', + )) + response = await client.create_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateSubpropertyEventFilterRequest() + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_subproperty_event_filter in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_subproperty_event_filter] = mock_object + + request = {} + await client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateSubpropertyEventFilterRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gaa_subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_value', + )) + response = await client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == 'name_value' + assert response.apply_to_property == 'apply_to_property_value' + + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_async_from_dict(): + await test_create_subproperty_event_filter_async(request_type=dict) + + +def test_create_subproperty_event_filter_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateSubpropertyEventFilterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), + '__call__') as call: + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_subproperty_event_filter_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateSubpropertyEventFilterRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_subproperty_event_filter.SubpropertyEventFilter()) + await client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_subproperty_event_filter_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_subproperty_event_filter( + parent='parent_value', + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(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].subproperty_event_filter + mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter(name='name_value') + assert arg == mock_val + + +def test_create_subproperty_event_filter_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filter( + analytics_admin.CreateSubpropertyEventFilterRequest(), + parent='parent_value', + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_subproperty_event_filter.SubpropertyEventFilter()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_subproperty_event_filter( + parent='parent_value', + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(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].subproperty_event_filter + mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_subproperty_event_filter_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_subproperty_event_filter( + analytics_admin.CreateSubpropertyEventFilterRequest(), + parent='parent_value', + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetSubpropertyEventFilterRequest, + dict, +]) +def test_get_subproperty_event_filter(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_value', + ) + response = client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, subproperty_event_filter.SubpropertyEventFilter) + assert response.name == 'name_value' + assert response.apply_to_property == 'apply_to_property_value' + + +def test_get_subproperty_event_filter_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filter), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSubpropertyEventFilterRequest() + + +def test_get_subproperty_event_filter_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetSubpropertyEventFilterRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_subproperty_event_filter(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSubpropertyEventFilterRequest( + name='name_value', + ) + +def test_get_subproperty_event_filter_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_subproperty_event_filter in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_subproperty_event_filter] = mock_rpc + request = {} + client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_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 = AnalyticsAdminServiceAsyncClient( + 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_value', + )) + response = await client.get_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetSubpropertyEventFilterRequest() + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_subproperty_event_filter in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_subproperty_event_filter] = mock_object + + request = {} + await client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetSubpropertyEventFilterRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_value', + )) + response = await client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, subproperty_event_filter.SubpropertyEventFilter) + assert response.name == 'name_value' + assert response.apply_to_property == 'apply_to_property_value' + + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_async_from_dict(): + await test_get_subproperty_event_filter_async(request_type=dict) + + +def test_get_subproperty_event_filter_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetSubpropertyEventFilterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), + '__call__') as call: + call.return_value = subproperty_event_filter.SubpropertyEventFilter() + client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_subproperty_event_filter_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetSubpropertyEventFilterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(subproperty_event_filter.SubpropertyEventFilter()) + await client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_subproperty_event_filter_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = subproperty_event_filter.SubpropertyEventFilter() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_subproperty_event_filter( + 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_subproperty_event_filter_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filter( + analytics_admin.GetSubpropertyEventFilterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_subproperty_event_filter_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = subproperty_event_filter.SubpropertyEventFilter() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(subproperty_event_filter.SubpropertyEventFilter()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_subproperty_event_filter( + 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_subproperty_event_filter_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_subproperty_event_filter( + analytics_admin.GetSubpropertyEventFilterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListSubpropertyEventFiltersRequest, + dict, +]) +def test_list_subproperty_event_filters(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse( + next_page_token='next_page_token_value', + ) + response = client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListSubpropertyEventFiltersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubpropertyEventFiltersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_subproperty_event_filters_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_subproperty_event_filters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSubpropertyEventFiltersRequest() + + +def test_list_subproperty_event_filters_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListSubpropertyEventFiltersRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_subproperty_event_filters(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSubpropertyEventFiltersRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_subproperty_event_filters_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_subproperty_event_filters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_subproperty_event_filters] = mock_rpc + request = {} + client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_subproperty_event_filters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_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 = AnalyticsAdminServiceAsyncClient( + 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_subproperty_event_filters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSubpropertyEventFiltersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_subproperty_event_filters() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListSubpropertyEventFiltersRequest() + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_subproperty_event_filters in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_subproperty_event_filters] = mock_object + + request = {} + await client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_subproperty_event_filters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListSubpropertyEventFiltersRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSubpropertyEventFiltersResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListSubpropertyEventFiltersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubpropertyEventFiltersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_async_from_dict(): + await test_list_subproperty_event_filters_async(request_type=dict) + + +def test_list_subproperty_event_filters_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListSubpropertyEventFiltersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), + '__call__') as call: + call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() + client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_subproperty_event_filters_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListSubpropertyEventFiltersRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSubpropertyEventFiltersResponse()) + await client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_subproperty_event_filters_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_subproperty_event_filters( + 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_subproperty_event_filters_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filters( + analytics_admin.ListSubpropertyEventFiltersRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListSubpropertyEventFiltersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_subproperty_event_filters( + 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_subproperty_event_filters_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_subproperty_event_filters( + analytics_admin.ListSubpropertyEventFiltersRequest(), + parent='parent_value', + ) + + +def test_list_subproperty_event_filters_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_subproperty_event_filters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='abc', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[], + next_page_token='def', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_subproperty_event_filters(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, subproperty_event_filter.SubpropertyEventFilter) + for i in results) +def test_list_subproperty_event_filters_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_subproperty_event_filters), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='abc', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[], + next_page_token='def', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + ), + RuntimeError, + ) + pages = list(client.list_subproperty_event_filters(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_subproperty_event_filters_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='abc', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[], + next_page_token='def', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_subproperty_event_filters(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, subproperty_event_filter.SubpropertyEventFilter) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_subproperty_event_filters_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_subproperty_event_filters), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='abc', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[], + next_page_token='def', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + ), + 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_subproperty_event_filters(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", [ + analytics_admin.UpdateSubpropertyEventFilterRequest, + dict, +]) +def test_update_subproperty_event_filter(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_value', + ) + response = client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == 'name_value' + assert response.apply_to_property == 'apply_to_property_value' + + +def test_update_subproperty_event_filter_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filter), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSubpropertyEventFilterRequest() + + +def test_update_subproperty_event_filter_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateSubpropertyEventFilterRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_subproperty_event_filter(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSubpropertyEventFilterRequest( + ) + +def test_update_subproperty_event_filter_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_subproperty_event_filter in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_subproperty_event_filter] = mock_rpc + request = {} + client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_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 = AnalyticsAdminServiceAsyncClient( + 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_value', + )) + response = await client.update_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateSubpropertyEventFilterRequest() + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_subproperty_event_filter in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_subproperty_event_filter] = mock_object + + request = {} + await client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateSubpropertyEventFilterRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(gaa_subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_value', + )) + response = await client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == 'name_value' + assert response.apply_to_property == 'apply_to_property_value' + + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_async_from_dict(): + await test_update_subproperty_event_filter_async(request_type=dict) + + +def test_update_subproperty_event_filter_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + + request.subproperty_event_filter.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), + '__call__') as call: + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subproperty_event_filter.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + + request.subproperty_event_filter.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_subproperty_event_filter.SubpropertyEventFilter()) + await client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'subproperty_event_filter.name=name_value', + ) in kw['metadata'] + + +def test_update_subproperty_event_filter_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_subproperty_event_filter( + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(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].subproperty_event_filter + mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter(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_subproperty_event_filter_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filter( + analytics_admin.UpdateSubpropertyEventFilterRequest(), + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_subproperty_event_filter_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gaa_subproperty_event_filter.SubpropertyEventFilter()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_subproperty_event_filter( + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(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].subproperty_event_filter + mock_val = gaa_subproperty_event_filter.SubpropertyEventFilter(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_subproperty_event_filter_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_subproperty_event_filter( + analytics_admin.UpdateSubpropertyEventFilterRequest(), + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteSubpropertyEventFilterRequest, + dict, +]) +def test_delete_subproperty_event_filter(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteSubpropertyEventFilterRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_subproperty_event_filter_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filter), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSubpropertyEventFilterRequest() + + +def test_delete_subproperty_event_filter_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteSubpropertyEventFilterRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_subproperty_event_filter(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSubpropertyEventFilterRequest( + name='name_value', + ) + +def test_delete_subproperty_event_filter_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_subproperty_event_filter in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_subproperty_event_filter] = mock_rpc + request = {} + client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_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 = AnalyticsAdminServiceAsyncClient( + 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_subproperty_event_filter() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteSubpropertyEventFilterRequest() + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_subproperty_event_filter in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_subproperty_event_filter] = mock_object + + request = {} + await client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteSubpropertyEventFilterRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_subproperty_event_filter), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteSubpropertyEventFilterRequest() + 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_subproperty_event_filter_async_from_dict(): + await test_delete_subproperty_event_filter_async(request_type=dict) + + +def test_delete_subproperty_event_filter_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteSubpropertyEventFilterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), + '__call__') as call: + call.return_value = None + client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_subproperty_event_filter_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteSubpropertyEventFilterRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_subproperty_event_filter_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), + '__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_subproperty_event_filter( + 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_subproperty_event_filter_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_subproperty_event_filter( + analytics_admin.DeleteSubpropertyEventFilterRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_subproperty_event_filter_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_subproperty_event_filter), + '__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_subproperty_event_filter( + 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_subproperty_event_filter_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_subproperty_event_filter( + analytics_admin.DeleteSubpropertyEventFilterRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAccountRequest, + dict, +]) +def test_get_account_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/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 = resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_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 = resources.Account.pb(return_value) + 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_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + +def test_get_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account] = mock_rpc + + request = {} + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_account_rest_required_fields(request_type=analytics_admin.GetAccountRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_account._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_account._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Account() + # 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 = resources.Account.pb(return_value) + 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_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_account_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_account_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_account") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_account") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetAccountRequest.pb(analytics_admin.GetAccountRequest()) + 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 = resources.Account.to_json(resources.Account()) + + request = analytics_admin.GetAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Account() + + client.get_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_account_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetAccountRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/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_account(request) + + +def test_get_account_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Account() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/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 = resources.Account.pb(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_account(**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/v1alpha/{name=accounts/*}" % client.transport._host, args[1]) + + +def test_get_account_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_account( + analytics_admin.GetAccountRequest(), + name='name_value', + ) + + +def test_get_account_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccountsRequest, + dict, +]) +def test_list_accounts_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccountsResponse( + 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 = analytics_admin.ListAccountsResponse.pb(return_value) + 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_accounts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_accounts_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_accounts] = mock_rpc + + request = {} + client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accounts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_accounts_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_accounts") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_accounts") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListAccountsRequest.pb(analytics_admin.ListAccountsRequest()) + 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 = analytics_admin.ListAccountsResponse.to_json(analytics_admin.ListAccountsResponse()) + + request = analytics_admin.ListAccountsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListAccountsResponse() + + client.list_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_accounts_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListAccountsRequest): + client = AnalyticsAdminServiceClient( + 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_accounts(request) + + +def test_list_accounts_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListAccountsResponse.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_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Account) + for i in results) + + pages = list(client.list_accounts(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", [ + analytics_admin.DeleteAccountRequest, + dict, +]) +def test_delete_account_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/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_account(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_account] = mock_rpc + + request = {} + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_account_rest_required_fields(request_type=analytics_admin.DeleteAccountRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_account._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_account._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 = AnalyticsAdminServiceClient( + 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_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_account_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_account_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_account") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteAccountRequest.pb(analytics_admin.DeleteAccountRequest()) + 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 = analytics_admin.DeleteAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_account_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteAccountRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/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_account(request) + + +def test_delete_account_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'accounts/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_account(**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/v1alpha/{name=accounts/*}" % client.transport._host, args[1]) + + +def test_delete_account_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_account( + analytics_admin.DeleteAccountRequest(), + name='name_value', + ) + + +def test_delete_account_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAccountRequest, + dict, +]) +def test_update_account_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'account': {'name': 'accounts/sample1'}} + request_init["account"] = {'name': 'accounts/sample1', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'display_name': 'display_name_value', 'region_code': 'region_code_value', 'deleted': True, 'gmp_organization': 'gmp_organization_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 = analytics_admin.UpdateAccountRequest.meta.fields["account"] + + 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["account"].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["account"][field])): + del request_init["account"][field][i][subfield] + else: + del request_init["account"][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 = resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_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 = resources.Account.pb(return_value) + 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_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + +def test_update_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + + request = {} + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_account_rest_required_fields(request_type=analytics_admin.UpdateAccountRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_account._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_account._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Account() + # 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 = resources.Account.pb(return_value) + 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_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_account_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("account", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_account_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_account") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_account") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateAccountRequest.pb(analytics_admin.UpdateAccountRequest()) + 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 = resources.Account.to_json(resources.Account()) + + request = analytics_admin.UpdateAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Account() + + client.update_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_account_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateAccountRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'account': {'name': 'accounts/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_account(request) + + +def test_update_account_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Account() + + # get arguments that satisfy an http rule for this method + sample_request = {'account': {'name': 'accounts/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + account=resources.Account(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 = resources.Account.pb(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_account(**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/v1alpha/{account.name=accounts/*}" % client.transport._host, args[1]) + + +def test_update_account_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_account( + analytics_admin.UpdateAccountRequest(), + account=resources.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_account_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ProvisionAccountTicketRequest, + dict, +]) +def test_provision_account_ticket_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ProvisionAccountTicketResponse( + account_ticket_id='account_ticket_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 = analytics_admin.ProvisionAccountTicketResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.provision_account_ticket(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionAccountTicketResponse) + assert response.account_ticket_id == 'account_ticket_id_value' + +def test_provision_account_ticket_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.provision_account_ticket in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.provision_account_ticket] = mock_rpc + + request = {} + client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provision_account_ticket(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_provision_account_ticket_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_provision_account_ticket") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_provision_account_ticket") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ProvisionAccountTicketRequest.pb(analytics_admin.ProvisionAccountTicketRequest()) + 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 = analytics_admin.ProvisionAccountTicketResponse.to_json(analytics_admin.ProvisionAccountTicketResponse()) + + request = analytics_admin.ProvisionAccountTicketRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ProvisionAccountTicketResponse() + + client.provision_account_ticket(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_provision_account_ticket_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ProvisionAccountTicketRequest): + client = AnalyticsAdminServiceClient( + 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.provision_account_ticket(request) + + +def test_provision_account_ticket_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccountSummariesRequest, + dict, +]) +def test_list_account_summaries_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccountSummariesResponse( + 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 = analytics_admin.ListAccountSummariesResponse.pb(return_value) + 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_account_summaries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountSummariesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_account_summaries_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_account_summaries in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_account_summaries] = mock_rpc + + request = {} + client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_summaries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_account_summaries_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_account_summaries") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_account_summaries") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListAccountSummariesRequest.pb(analytics_admin.ListAccountSummariesRequest()) + 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 = analytics_admin.ListAccountSummariesResponse.to_json(analytics_admin.ListAccountSummariesResponse()) + + request = analytics_admin.ListAccountSummariesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListAccountSummariesResponse() + + client.list_account_summaries(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_account_summaries_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListAccountSummariesRequest): + client = AnalyticsAdminServiceClient( + 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_account_summaries(request) + + +def test_list_account_summaries_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListAccountSummariesResponse.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_account_summaries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AccountSummary) + for i in results) + + pages = list(client.list_account_summaries(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", [ + analytics_admin.GetPropertyRequest, + dict, +]) +def test_get_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/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 = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_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 = resources.Property.pb(return_value) + 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_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + +def test_get_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_property] = mock_rpc + + request = {} + client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_property_rest_required_fields(request_type=analytics_admin.GetPropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_property._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_property._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # 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 = resources.Property.pb(return_value) + 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_property(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetPropertyRequest.pb(analytics_admin.GetPropertyRequest()) + 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 = resources.Property.to_json(resources.Property()) + + request = analytics_admin.GetPropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.get_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetPropertyRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/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_property(request) + + +def test_get_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/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 = resources.Property.pb(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_property(**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/v1alpha/{name=properties/*}" % client.transport._host, args[1]) + + +def test_get_property_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_property( + analytics_admin.GetPropertyRequest(), + name='name_value', + ) + + +def test_get_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListPropertiesRequest, + dict, +]) +def test_list_properties_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListPropertiesResponse( + 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 = analytics_admin.ListPropertiesResponse.pb(return_value) + 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_properties(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPropertiesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_properties_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_properties in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_properties] = mock_rpc + + request = {} + client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_properties(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_properties_rest_required_fields(request_type=analytics_admin.ListPropertiesRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["filter"] = "" + 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 "filter" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_properties._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "filter" in jsonified_request + assert jsonified_request["filter"] == request_init["filter"] + + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_properties._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_deleted", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListPropertiesResponse() + # 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 = analytics_admin.ListPropertiesResponse.pb(return_value) + 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_properties(request) + + expected_params = [ + ( + "filter", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_properties_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_properties._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", "showDeleted", )) & set(("filter", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_properties_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_properties") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_properties") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListPropertiesRequest.pb(analytics_admin.ListPropertiesRequest()) + 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 = analytics_admin.ListPropertiesResponse.to_json(analytics_admin.ListPropertiesResponse()) + + request = analytics_admin.ListPropertiesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListPropertiesResponse() + + client.list_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_properties_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListPropertiesRequest): + client = AnalyticsAdminServiceClient( + 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_properties(request) + + +def test_list_properties_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListPropertiesResponse.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_properties(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Property) + for i in results) + + pages = list(client.list_properties(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", [ + analytics_admin.CreatePropertyRequest, + dict, +]) +def test_create_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["property"] = {'name': 'name_value', 'property_type': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'parent': 'parent_value', 'display_name': 'display_name_value', 'industry_category': 1, 'time_zone': 'time_zone_value', 'currency_code': 'currency_code_value', 'service_level': 1, 'delete_time': {}, 'expire_time': {}, 'account': 'account_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 = analytics_admin.CreatePropertyRequest.meta.fields["property"] + + 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["property"].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["property"][field])): + del request_init["property"][field][i][subfield] + else: + del request_init["property"][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 = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_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 = resources.Property.pb(return_value) + 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_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + +def test_create_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_property] = mock_rpc + + request = {} + client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_property_rest_required_fields(request_type=analytics_admin.CreatePropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_property._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_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # 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 = resources.Property.pb(return_value) + 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_property(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("property", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreatePropertyRequest.pb(analytics_admin.CreatePropertyRequest()) + 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 = resources.Property.to_json(resources.Property()) + + request = analytics_admin.CreatePropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.create_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreatePropertyRequest): + client = AnalyticsAdminServiceClient( + 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_property(request) + + +def test_create_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + property=resources.Property(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 = resources.Property.pb(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_property(**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/v1alpha/properties" % client.transport._host, args[1]) + + +def test_create_property_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_property( + analytics_admin.CreatePropertyRequest(), + property=resources.Property(name='name_value'), + ) + + +def test_create_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeletePropertyRequest, + dict, +]) +def test_delete_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/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 = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_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 = resources.Property.pb(return_value) + 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_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + +def test_delete_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_property] = mock_rpc + + request = {} + client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_property_rest_required_fields(request_type=analytics_admin.DeletePropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_property._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_property._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # 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 = resources.Property.pb(return_value) + 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_property(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_delete_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.DeletePropertyRequest.pb(analytics_admin.DeletePropertyRequest()) + 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 = resources.Property.to_json(resources.Property()) + + request = analytics_admin.DeletePropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.delete_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeletePropertyRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/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_property(request) + + +def test_delete_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/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 = resources.Property.pb(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_property(**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/v1alpha/{name=properties/*}" % client.transport._host, args[1]) + + +def test_delete_property_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_property( + analytics_admin.DeletePropertyRequest(), + name='name_value', + ) + + +def test_delete_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdatePropertyRequest, + dict, +]) +def test_update_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'property': {'name': 'properties/sample1'}} + request_init["property"] = {'name': 'properties/sample1', 'property_type': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'parent': 'parent_value', 'display_name': 'display_name_value', 'industry_category': 1, 'time_zone': 'time_zone_value', 'currency_code': 'currency_code_value', 'service_level': 1, 'delete_time': {}, 'expire_time': {}, 'account': 'account_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 = analytics_admin.UpdatePropertyRequest.meta.fields["property"] + + 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["property"].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["property"][field])): + del request_init["property"][field][i][subfield] + else: + del request_init["property"][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 = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_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 = resources.Property.pb(return_value) + 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_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + +def test_update_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_property] = mock_rpc + + request = {} + client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_property_rest_required_fields(request_type=analytics_admin.UpdatePropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_property._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_property._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # 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 = resources.Property.pb(return_value) + 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_property(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("property", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdatePropertyRequest.pb(analytics_admin.UpdatePropertyRequest()) + 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 = resources.Property.to_json(resources.Property()) + + request = analytics_admin.UpdatePropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.update_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdatePropertyRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'property': {'name': 'properties/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_property(request) + + +def test_update_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {'property': {'name': 'properties/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + property=resources.Property(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 = resources.Property.pb(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_property(**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/v1alpha/{property.name=properties/*}" % client.transport._host, args[1]) + + +def test_update_property_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_property( + analytics_admin.UpdatePropertyRequest(), + property=resources.Property(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateFirebaseLinkRequest, + dict, +]) +def test_create_firebase_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["firebase_link"] = {'name': 'name_value', 'project': 'project_value', 'create_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 = analytics_admin.CreateFirebaseLinkRequest.meta.fields["firebase_link"] + + 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["firebase_link"].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["firebase_link"][field])): + del request_init["firebase_link"][field][i][subfield] + else: + del request_init["firebase_link"][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 = resources.FirebaseLink( + name='name_value', + project='project_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 = resources.FirebaseLink.pb(return_value) + 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_firebase_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.FirebaseLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + +def test_create_firebase_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_firebase_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_firebase_link] = mock_rpc + + request = {} + client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_firebase_link_rest_required_fields(request_type=analytics_admin.CreateFirebaseLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_firebase_link._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_firebase_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.FirebaseLink() + # 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 = resources.FirebaseLink.pb(return_value) + 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_firebase_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_firebase_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_firebase_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "firebaseLink", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_firebase_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_firebase_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_firebase_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateFirebaseLinkRequest.pb(analytics_admin.CreateFirebaseLinkRequest()) + 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 = resources.FirebaseLink.to_json(resources.FirebaseLink()) + + request = analytics_admin.CreateFirebaseLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.FirebaseLink() + + client.create_firebase_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_firebase_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateFirebaseLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_firebase_link(request) + + +def test_create_firebase_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.FirebaseLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + firebase_link=resources.FirebaseLink(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 = resources.FirebaseLink.pb(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_firebase_link(**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/v1alpha/{parent=properties/*}/firebaseLinks" % client.transport._host, args[1]) + + +def test_create_firebase_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_firebase_link( + analytics_admin.CreateFirebaseLinkRequest(), + parent='parent_value', + firebase_link=resources.FirebaseLink(name='name_value'), + ) + + +def test_create_firebase_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteFirebaseLinkRequest, + dict, +]) +def test_delete_firebase_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/firebaseLinks/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_firebase_link(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_firebase_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_firebase_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_firebase_link] = mock_rpc + + request = {} + client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_firebase_link_rest_required_fields(request_type=analytics_admin.DeleteFirebaseLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_firebase_link._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_firebase_link._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 = AnalyticsAdminServiceClient( + 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_firebase_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_firebase_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_firebase_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_firebase_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_firebase_link") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteFirebaseLinkRequest.pb(analytics_admin.DeleteFirebaseLinkRequest()) + 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 = analytics_admin.DeleteFirebaseLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_firebase_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_firebase_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteFirebaseLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/firebaseLinks/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_firebase_link(request) + + +def test_delete_firebase_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/firebaseLinks/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_firebase_link(**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/v1alpha/{name=properties/*/firebaseLinks/*}" % client.transport._host, args[1]) + + +def test_delete_firebase_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_firebase_link( + analytics_admin.DeleteFirebaseLinkRequest(), + name='name_value', + ) + + +def test_delete_firebase_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListFirebaseLinksRequest, + dict, +]) +def test_list_firebase_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListFirebaseLinksResponse( + 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 = analytics_admin.ListFirebaseLinksResponse.pb(return_value) + 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_firebase_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirebaseLinksPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_firebase_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_firebase_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_firebase_links] = mock_rpc + + request = {} + client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_firebase_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_firebase_links_rest_required_fields(request_type=analytics_admin.ListFirebaseLinksRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_firebase_links._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_firebase_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListFirebaseLinksResponse() + # 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 = analytics_admin.ListFirebaseLinksResponse.pb(return_value) + 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_firebase_links(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_firebase_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_firebase_links._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_firebase_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_firebase_links") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_firebase_links") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListFirebaseLinksRequest.pb(analytics_admin.ListFirebaseLinksRequest()) + 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 = analytics_admin.ListFirebaseLinksResponse.to_json(analytics_admin.ListFirebaseLinksResponse()) + + request = analytics_admin.ListFirebaseLinksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListFirebaseLinksResponse() + + client.list_firebase_links(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_firebase_links_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListFirebaseLinksRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_firebase_links(request) + + +def test_list_firebase_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListFirebaseLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListFirebaseLinksResponse.pb(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_firebase_links(**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/v1alpha/{parent=properties/*}/firebaseLinks" % client.transport._host, args[1]) + + +def test_list_firebase_links_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_firebase_links( + analytics_admin.ListFirebaseLinksRequest(), + parent='parent_value', + ) + + +def test_list_firebase_links_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListFirebaseLinksResponse.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': 'properties/sample1'} + + pager = client.list_firebase_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.FirebaseLink) + for i in results) + + pages = list(client.list_firebase_links(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", [ + analytics_admin.GetGlobalSiteTagRequest, + dict, +]) +def test_get_global_site_tag_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/globalSiteTag'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.GlobalSiteTag( + name='name_value', + snippet='snippet_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 = resources.GlobalSiteTag.pb(return_value) + 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_global_site_tag(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GlobalSiteTag) + assert response.name == 'name_value' + assert response.snippet == 'snippet_value' + +def test_get_global_site_tag_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_global_site_tag in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_global_site_tag] = mock_rpc + + request = {} + client.get_global_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_global_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_global_site_tag_rest_required_fields(request_type=analytics_admin.GetGlobalSiteTagRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_global_site_tag._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_global_site_tag._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.GlobalSiteTag() + # 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 = resources.GlobalSiteTag.pb(return_value) + 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_global_site_tag(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_global_site_tag_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_global_site_tag._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_global_site_tag_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_global_site_tag") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_global_site_tag") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetGlobalSiteTagRequest.pb(analytics_admin.GetGlobalSiteTagRequest()) + 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 = resources.GlobalSiteTag.to_json(resources.GlobalSiteTag()) + + request = analytics_admin.GetGlobalSiteTagRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.GlobalSiteTag() + + client.get_global_site_tag(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_global_site_tag_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetGlobalSiteTagRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/globalSiteTag'} + 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_global_site_tag(request) + + +def test_get_global_site_tag_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.GlobalSiteTag() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/sample2/globalSiteTag'} + + # 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 = resources.GlobalSiteTag.pb(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_global_site_tag(**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/v1alpha/{name=properties/*/dataStreams/*/globalSiteTag}" % client.transport._host, args[1]) + + +def test_get_global_site_tag_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_global_site_tag( + analytics_admin.GetGlobalSiteTagRequest(), + name='name_value', + ) + + +def test_get_global_site_tag_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateGoogleAdsLinkRequest, + dict, +]) +def test_create_google_ads_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["google_ads_link"] = {'name': 'name_value', 'customer_id': 'customer_id_value', 'can_manage_clients': True, 'ads_personalization_enabled': {'value': True}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'creator_email_address': 'creator_email_address_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 = analytics_admin.CreateGoogleAdsLinkRequest.meta.fields["google_ads_link"] + + 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["google_ads_link"].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["google_ads_link"][field])): + del request_init["google_ads_link"][field][i][subfield] + else: + del request_init["google_ads_link"][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 = resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_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 = resources.GoogleAdsLink.pb(return_value) + 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_google_ads_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + +def test_create_google_ads_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_google_ads_link] = mock_rpc + + request = {} + client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_google_ads_link_rest_required_fields(request_type=analytics_admin.CreateGoogleAdsLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_ads_link._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_google_ads_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.GoogleAdsLink() + # 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 = resources.GoogleAdsLink.pb(return_value) + 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_google_ads_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_google_ads_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_google_ads_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "googleAdsLink", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_google_ads_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_google_ads_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_google_ads_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateGoogleAdsLinkRequest.pb(analytics_admin.CreateGoogleAdsLinkRequest()) + 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 = resources.GoogleAdsLink.to_json(resources.GoogleAdsLink()) + + request = analytics_admin.CreateGoogleAdsLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.GoogleAdsLink() + + client.create_google_ads_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_google_ads_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateGoogleAdsLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_google_ads_link(request) + + +def test_create_google_ads_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.GoogleAdsLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(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 = resources.GoogleAdsLink.pb(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_google_ads_link(**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/v1alpha/{parent=properties/*}/googleAdsLinks" % client.transport._host, args[1]) + + +def test_create_google_ads_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_ads_link( + analytics_admin.CreateGoogleAdsLinkRequest(), + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(name='name_value'), + ) + + +def test_create_google_ads_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateGoogleAdsLinkRequest, + dict, +]) +def test_update_google_ads_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'google_ads_link': {'name': 'properties/sample1/googleAdsLinks/sample2'}} + request_init["google_ads_link"] = {'name': 'properties/sample1/googleAdsLinks/sample2', 'customer_id': 'customer_id_value', 'can_manage_clients': True, 'ads_personalization_enabled': {'value': True}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'creator_email_address': 'creator_email_address_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 = analytics_admin.UpdateGoogleAdsLinkRequest.meta.fields["google_ads_link"] + + 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["google_ads_link"].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["google_ads_link"][field])): + del request_init["google_ads_link"][field][i][subfield] + else: + del request_init["google_ads_link"][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 = resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_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 = resources.GoogleAdsLink.pb(return_value) + 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_google_ads_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + +def test_update_google_ads_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_google_ads_link] = mock_rpc + + request = {} + client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_google_ads_link_rest_required_fields(request_type=analytics_admin.UpdateGoogleAdsLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_ads_link._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_google_ads_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.GoogleAdsLink() + # 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 = resources.GoogleAdsLink.pb(return_value) + 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_google_ads_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_google_ads_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_google_ads_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_google_ads_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_google_ads_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_google_ads_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateGoogleAdsLinkRequest.pb(analytics_admin.UpdateGoogleAdsLinkRequest()) + 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 = resources.GoogleAdsLink.to_json(resources.GoogleAdsLink()) + + request = analytics_admin.UpdateGoogleAdsLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.GoogleAdsLink() + + client.update_google_ads_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_google_ads_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateGoogleAdsLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'google_ads_link': {'name': 'properties/sample1/googleAdsLinks/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_google_ads_link(request) + + +def test_update_google_ads_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.GoogleAdsLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'google_ads_link': {'name': 'properties/sample1/googleAdsLinks/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + google_ads_link=resources.GoogleAdsLink(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 = resources.GoogleAdsLink.pb(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_google_ads_link(**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/v1alpha/{google_ads_link.name=properties/*/googleAdsLinks/*}" % client.transport._host, args[1]) + + +def test_update_google_ads_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_ads_link( + analytics_admin.UpdateGoogleAdsLinkRequest(), + google_ads_link=resources.GoogleAdsLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_google_ads_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteGoogleAdsLinkRequest, + dict, +]) +def test_delete_google_ads_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/googleAdsLinks/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_google_ads_link(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_google_ads_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_google_ads_link] = mock_rpc + + request = {} + client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_google_ads_link_rest_required_fields(request_type=analytics_admin.DeleteGoogleAdsLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_ads_link._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_google_ads_link._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 = AnalyticsAdminServiceClient( + 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_google_ads_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_google_ads_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_google_ads_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_google_ads_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_google_ads_link") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteGoogleAdsLinkRequest.pb(analytics_admin.DeleteGoogleAdsLinkRequest()) + 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 = analytics_admin.DeleteGoogleAdsLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_google_ads_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_google_ads_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteGoogleAdsLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/googleAdsLinks/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_google_ads_link(request) + + +def test_delete_google_ads_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/googleAdsLinks/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_google_ads_link(**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/v1alpha/{name=properties/*/googleAdsLinks/*}" % client.transport._host, args[1]) + + +def test_delete_google_ads_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_ads_link( + analytics_admin.DeleteGoogleAdsLinkRequest(), + name='name_value', + ) + + +def test_delete_google_ads_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListGoogleAdsLinksRequest, + dict, +]) +def test_list_google_ads_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListGoogleAdsLinksResponse( + 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 = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) + 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_google_ads_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleAdsLinksPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_google_ads_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_google_ads_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_google_ads_links] = mock_rpc + + request = {} + client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_google_ads_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_google_ads_links_rest_required_fields(request_type=analytics_admin.ListGoogleAdsLinksRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_ads_links._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_google_ads_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListGoogleAdsLinksResponse() + # 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 = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) + 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_google_ads_links(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_google_ads_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_google_ads_links._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_google_ads_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_google_ads_links") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_google_ads_links") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListGoogleAdsLinksRequest.pb(analytics_admin.ListGoogleAdsLinksRequest()) + 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 = analytics_admin.ListGoogleAdsLinksResponse.to_json(analytics_admin.ListGoogleAdsLinksResponse()) + + request = analytics_admin.ListGoogleAdsLinksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListGoogleAdsLinksResponse() + + client.list_google_ads_links(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_google_ads_links_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListGoogleAdsLinksRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_google_ads_links(request) + + +def test_list_google_ads_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListGoogleAdsLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListGoogleAdsLinksResponse.pb(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_google_ads_links(**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/v1alpha/{parent=properties/*}/googleAdsLinks" % client.transport._host, args[1]) + + +def test_list_google_ads_links_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_ads_links( + analytics_admin.ListGoogleAdsLinksRequest(), + parent='parent_value', + ) + + +def test_list_google_ads_links_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListGoogleAdsLinksResponse.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': 'properties/sample1'} + + pager = client.list_google_ads_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.GoogleAdsLink) + for i in results) + + pages = list(client.list_google_ads_links(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", [ + analytics_admin.GetDataSharingSettingsRequest, + dict, +]) +def test_get_data_sharing_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSharingSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataSharingSettings( + name='name_value', + sharing_with_google_support_enabled=True, + sharing_with_google_assigned_sales_enabled=True, + sharing_with_google_any_sales_enabled=True, + sharing_with_google_products_enabled=True, + sharing_with_others_enabled=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 = resources.DataSharingSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_sharing_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataSharingSettings) + assert response.name == 'name_value' + assert response.sharing_with_google_support_enabled is True + assert response.sharing_with_google_assigned_sales_enabled is True + assert response.sharing_with_google_any_sales_enabled is True + assert response.sharing_with_google_products_enabled is True + assert response.sharing_with_others_enabled is True + +def test_get_data_sharing_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_sharing_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_sharing_settings] = mock_rpc + + request = {} + client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_sharing_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_sharing_settings_rest_required_fields(request_type=analytics_admin.GetDataSharingSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_sharing_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_sharing_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataSharingSettings() + # 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 = resources.DataSharingSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_sharing_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_sharing_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_sharing_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_sharing_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_data_sharing_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_sharing_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetDataSharingSettingsRequest.pb(analytics_admin.GetDataSharingSettingsRequest()) + 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 = resources.DataSharingSettings.to_json(resources.DataSharingSettings()) + + request = analytics_admin.GetDataSharingSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataSharingSettings() + + client.get_data_sharing_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_sharing_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetDataSharingSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSharingSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_data_sharing_settings(request) + + +def test_get_data_sharing_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataSharingSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/dataSharingSettings'} + + # 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 = resources.DataSharingSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_sharing_settings(**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/v1alpha/{name=accounts/*/dataSharingSettings}" % client.transport._host, args[1]) + + +def test_get_data_sharing_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_sharing_settings( + analytics_admin.GetDataSharingSettingsRequest(), + name='name_value', + ) + + +def test_get_data_sharing_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetMeasurementProtocolSecretRequest, + dict, +]) +def test_get_measurement_protocol_secret_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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 = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + +def test_get_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_measurement_protocol_secret] = mock_rpc + + request = {} + client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_measurement_protocol_secret_rest_required_fields(request_type=analytics_admin.GetMeasurementProtocolSecretRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secret._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_measurement_protocol_secret._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.MeasurementProtocolSecret() + # 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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_measurement_protocol_secret_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_measurement_protocol_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_measurement_protocol_secret_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_measurement_protocol_secret") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_measurement_protocol_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetMeasurementProtocolSecretRequest.pb(analytics_admin.GetMeasurementProtocolSecretRequest()) + 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 = resources.MeasurementProtocolSecret.to_json(resources.MeasurementProtocolSecret()) + + request = analytics_admin.GetMeasurementProtocolSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.MeasurementProtocolSecret() + + client.get_measurement_protocol_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_measurement_protocol_secret_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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_measurement_protocol_secret(request) + + +def test_get_measurement_protocol_secret_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.MeasurementProtocolSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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 = resources.MeasurementProtocolSecret.pb(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_measurement_protocol_secret(**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/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" % client.transport._host, args[1]) + + +def test_get_measurement_protocol_secret_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret( + analytics_admin.GetMeasurementProtocolSecretRequest(), + name='name_value', + ) + + +def test_get_measurement_protocol_secret_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListMeasurementProtocolSecretsRequest, + dict, +]) +def test_list_measurement_protocol_secrets_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListMeasurementProtocolSecretsResponse( + 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 = analytics_admin.ListMeasurementProtocolSecretsResponse.pb(return_value) + 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_measurement_protocol_secrets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeasurementProtocolSecretsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_measurement_protocol_secrets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_measurement_protocol_secrets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_measurement_protocol_secrets] = mock_rpc + + request = {} + client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_measurement_protocol_secrets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_measurement_protocol_secrets_rest_required_fields(request_type=analytics_admin.ListMeasurementProtocolSecretsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secrets._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_measurement_protocol_secrets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + # 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 = analytics_admin.ListMeasurementProtocolSecretsResponse.pb(return_value) + 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_measurement_protocol_secrets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_measurement_protocol_secrets_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_measurement_protocol_secrets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_measurement_protocol_secrets_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_measurement_protocol_secrets") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_measurement_protocol_secrets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListMeasurementProtocolSecretsRequest.pb(analytics_admin.ListMeasurementProtocolSecretsRequest()) + 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 = analytics_admin.ListMeasurementProtocolSecretsResponse.to_json(analytics_admin.ListMeasurementProtocolSecretsResponse()) + + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + + client.list_measurement_protocol_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_measurement_protocol_secrets_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListMeasurementProtocolSecretsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_measurement_protocol_secrets(request) + + +def test_list_measurement_protocol_secrets_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListMeasurementProtocolSecretsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListMeasurementProtocolSecretsResponse.pb(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_measurement_protocol_secrets(**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/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets" % client.transport._host, args[1]) + + +def test_list_measurement_protocol_secrets_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secrets( + analytics_admin.ListMeasurementProtocolSecretsRequest(), + parent='parent_value', + ) + + +def test_list_measurement_protocol_secrets_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListMeasurementProtocolSecretsResponse.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': 'properties/sample1/dataStreams/sample2'} + + pager = client.list_measurement_protocol_secrets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.MeasurementProtocolSecret) + for i in results) + + pages = list(client.list_measurement_protocol_secrets(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", [ + analytics_admin.CreateMeasurementProtocolSecretRequest, + dict, +]) +def test_create_measurement_protocol_secret_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/sample2'} + request_init["measurement_protocol_secret"] = {'name': 'name_value', 'display_name': 'display_name_value', 'secret_value': 'secret_value_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 = analytics_admin.CreateMeasurementProtocolSecretRequest.meta.fields["measurement_protocol_secret"] + + 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["measurement_protocol_secret"].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["measurement_protocol_secret"][field])): + del request_init["measurement_protocol_secret"][field][i][subfield] + else: + del request_init["measurement_protocol_secret"][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 = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + +def test_create_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_measurement_protocol_secret] = mock_rpc + + request = {} + client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_measurement_protocol_secret_rest_required_fields(request_type=analytics_admin.CreateMeasurementProtocolSecretRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secret._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_measurement_protocol_secret._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.MeasurementProtocolSecret() + # 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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_measurement_protocol_secret_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_measurement_protocol_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "measurementProtocolSecret", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_measurement_protocol_secret_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_measurement_protocol_secret") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_measurement_protocol_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateMeasurementProtocolSecretRequest.pb(analytics_admin.CreateMeasurementProtocolSecretRequest()) + 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 = resources.MeasurementProtocolSecret.to_json(resources.MeasurementProtocolSecret()) + + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.MeasurementProtocolSecret() + + client.create_measurement_protocol_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_measurement_protocol_secret_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_measurement_protocol_secret(request) + + +def test_create_measurement_protocol_secret_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.MeasurementProtocolSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(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 = resources.MeasurementProtocolSecret.pb(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_measurement_protocol_secret(**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/v1alpha/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets" % client.transport._host, args[1]) + + +def test_create_measurement_protocol_secret_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret( + analytics_admin.CreateMeasurementProtocolSecretRequest(), + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + ) + + +def test_create_measurement_protocol_secret_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteMeasurementProtocolSecretRequest, + dict, +]) +def test_delete_measurement_protocol_secret_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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_measurement_protocol_secret(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_measurement_protocol_secret] = mock_rpc + + request = {} + client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_measurement_protocol_secret_rest_required_fields(request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secret._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_measurement_protocol_secret._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 = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_measurement_protocol_secret_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_measurement_protocol_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_measurement_protocol_secret_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_measurement_protocol_secret") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteMeasurementProtocolSecretRequest.pb(analytics_admin.DeleteMeasurementProtocolSecretRequest()) + 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 = analytics_admin.DeleteMeasurementProtocolSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_measurement_protocol_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_measurement_protocol_secret_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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_measurement_protocol_secret(request) + + +def test_delete_measurement_protocol_secret_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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_measurement_protocol_secret(**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/v1alpha/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" % client.transport._host, args[1]) + + +def test_delete_measurement_protocol_secret_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret( + analytics_admin.DeleteMeasurementProtocolSecretRequest(), + name='name_value', + ) + + +def test_delete_measurement_protocol_secret_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateMeasurementProtocolSecretRequest, + dict, +]) +def test_update_measurement_protocol_secret_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'measurement_protocol_secret': {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3'}} + request_init["measurement_protocol_secret"] = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3', 'display_name': 'display_name_value', 'secret_value': 'secret_value_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 = analytics_admin.UpdateMeasurementProtocolSecretRequest.meta.fields["measurement_protocol_secret"] + + 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["measurement_protocol_secret"].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["measurement_protocol_secret"][field])): + del request_init["measurement_protocol_secret"][field][i][subfield] + else: + del request_init["measurement_protocol_secret"][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 = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + +def test_update_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_measurement_protocol_secret] = mock_rpc + + request = {} + client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_measurement_protocol_secret_rest_required_fields(request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secret._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_measurement_protocol_secret._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.MeasurementProtocolSecret() + # 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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_measurement_protocol_secret_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_measurement_protocol_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("measurementProtocolSecret", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_measurement_protocol_secret_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_measurement_protocol_secret") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_measurement_protocol_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateMeasurementProtocolSecretRequest.pb(analytics_admin.UpdateMeasurementProtocolSecretRequest()) + 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 = resources.MeasurementProtocolSecret.to_json(resources.MeasurementProtocolSecret()) + + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.MeasurementProtocolSecret() + + client.update_measurement_protocol_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_measurement_protocol_secret_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'measurement_protocol_secret': {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_measurement_protocol_secret(request) + + +def test_update_measurement_protocol_secret_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.MeasurementProtocolSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'measurement_protocol_secret': {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + measurement_protocol_secret=resources.MeasurementProtocolSecret(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 = resources.MeasurementProtocolSecret.pb(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_measurement_protocol_secret(**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/v1alpha/{measurement_protocol_secret.name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" % client.transport._host, args[1]) + + +def test_update_measurement_protocol_secret_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret( + analytics_admin.UpdateMeasurementProtocolSecretRequest(), + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_measurement_protocol_secret_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.AcknowledgeUserDataCollectionRequest, + dict, +]) +def test_acknowledge_user_data_collection_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'property': 'properties/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 = analytics_admin.AcknowledgeUserDataCollectionResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.AcknowledgeUserDataCollectionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.acknowledge_user_data_collection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.AcknowledgeUserDataCollectionResponse) + +def test_acknowledge_user_data_collection_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.acknowledge_user_data_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.acknowledge_user_data_collection] = mock_rpc + + request = {} + client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.acknowledge_user_data_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_acknowledge_user_data_collection_rest_required_fields(request_type=analytics_admin.AcknowledgeUserDataCollectionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["property"] = "" + request_init["acknowledgement"] = "" + 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()).acknowledge_user_data_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["property"] = 'property_value' + jsonified_request["acknowledgement"] = 'acknowledgement_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).acknowledge_user_data_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "property" in jsonified_request + assert jsonified_request["property"] == 'property_value' + assert "acknowledgement" in jsonified_request + assert jsonified_request["acknowledgement"] == 'acknowledgement_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() + # 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 = analytics_admin.AcknowledgeUserDataCollectionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.acknowledge_user_data_collection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_acknowledge_user_data_collection_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.acknowledge_user_data_collection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("property", "acknowledgement", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_acknowledge_user_data_collection_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_acknowledge_user_data_collection") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_acknowledge_user_data_collection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.AcknowledgeUserDataCollectionRequest.pb(analytics_admin.AcknowledgeUserDataCollectionRequest()) + 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 = analytics_admin.AcknowledgeUserDataCollectionResponse.to_json(analytics_admin.AcknowledgeUserDataCollectionResponse()) + + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() + + client.acknowledge_user_data_collection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_acknowledge_user_data_collection_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.AcknowledgeUserDataCollectionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'property': 'properties/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.acknowledge_user_data_collection(request) + + +def test_acknowledge_user_data_collection_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetSKAdNetworkConversionValueSchemaRequest, + dict, +]) +def test_get_sk_ad_network_conversion_value_schema_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/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 = resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=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 = resources.SKAdNetworkConversionValueSchema.pb(return_value) + 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_sk_ad_network_conversion_value_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == 'name_value' + assert response.apply_conversion_values is True + +def test_get_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_sk_ad_network_conversion_value_schema] = mock_rpc + + request = {} + client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_sk_ad_network_conversion_value_schema_rest_required_fields(request_type=analytics_admin.GetSKAdNetworkConversionValueSchemaRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_sk_ad_network_conversion_value_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_sk_ad_network_conversion_value_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.SKAdNetworkConversionValueSchema() + # 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 = resources.SKAdNetworkConversionValueSchema.pb(return_value) + 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_sk_ad_network_conversion_value_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_sk_ad_network_conversion_value_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_sk_ad_network_conversion_value_schema_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_sk_ad_network_conversion_value_schema") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_sk_ad_network_conversion_value_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest.pb(analytics_admin.GetSKAdNetworkConversionValueSchemaRequest()) + 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 = resources.SKAdNetworkConversionValueSchema.to_json(resources.SKAdNetworkConversionValueSchema()) + + request = analytics_admin.GetSKAdNetworkConversionValueSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.SKAdNetworkConversionValueSchema() + + client.get_sk_ad_network_conversion_value_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_sk_ad_network_conversion_value_schema_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetSKAdNetworkConversionValueSchemaRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/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_sk_ad_network_conversion_value_schema(request) + + +def test_get_sk_ad_network_conversion_value_schema_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.SKAdNetworkConversionValueSchema() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/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 = resources.SKAdNetworkConversionValueSchema.pb(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_sk_ad_network_conversion_value_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}" % client.transport._host, args[1]) + + +def test_get_sk_ad_network_conversion_value_schema_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_sk_ad_network_conversion_value_schema( + analytics_admin.GetSKAdNetworkConversionValueSchemaRequest(), + name='name_value', + ) + + +def test_get_sk_ad_network_conversion_value_schema_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest, + dict, +]) +def test_create_sk_ad_network_conversion_value_schema_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/sample2'} + request_init["skadnetwork_conversion_value_schema"] = {'name': 'name_value', 'postback_window_one': {'conversion_values': [{'display_name': 'display_name_value', 'fine_value': 1054, 'coarse_value': 1, 'event_mappings': [{'event_name': 'event_name_value', 'min_event_count': 1613, 'max_event_count': 1615, 'min_event_value': 0.16010000000000002, 'max_event_value': 0.1603}], 'lock_enabled': True}], 'postback_window_settings_enabled': True}, 'postback_window_two': {}, 'postback_window_three': {}, 'apply_conversion_values': 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 = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest.meta.fields["skadnetwork_conversion_value_schema"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["skadnetwork_conversion_value_schema"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["skadnetwork_conversion_value_schema"][field])): + del request_init["skadnetwork_conversion_value_schema"][field][i][subfield] + else: + del request_init["skadnetwork_conversion_value_schema"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=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 = resources.SKAdNetworkConversionValueSchema.pb(return_value) + 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_sk_ad_network_conversion_value_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == 'name_value' + assert response.apply_conversion_values is True + +def test_create_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_sk_ad_network_conversion_value_schema] = mock_rpc + + request = {} + client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_sk_ad_network_conversion_value_schema_rest_required_fields(request_type=analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_sk_ad_network_conversion_value_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_sk_ad_network_conversion_value_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.SKAdNetworkConversionValueSchema() + # 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 = resources.SKAdNetworkConversionValueSchema.pb(return_value) + 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_sk_ad_network_conversion_value_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_sk_ad_network_conversion_value_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "skadnetworkConversionValueSchema", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_sk_ad_network_conversion_value_schema_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_sk_ad_network_conversion_value_schema") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_sk_ad_network_conversion_value_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest.pb(analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest()) + 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 = resources.SKAdNetworkConversionValueSchema.to_json(resources.SKAdNetworkConversionValueSchema()) + + request = analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.SKAdNetworkConversionValueSchema() + + client.create_sk_ad_network_conversion_value_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_sk_ad_network_conversion_value_schema_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_sk_ad_network_conversion_value_schema(request) + + +def test_create_sk_ad_network_conversion_value_schema_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.SKAdNetworkConversionValueSchema() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(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 = resources.SKAdNetworkConversionValueSchema.pb(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_sk_ad_network_conversion_value_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=properties/*/dataStreams/*}/sKAdNetworkConversionValueSchema" % client.transport._host, args[1]) + + +def test_create_sk_ad_network_conversion_value_schema_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_sk_ad_network_conversion_value_schema( + analytics_admin.CreateSKAdNetworkConversionValueSchemaRequest(), + parent='parent_value', + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(name='name_value'), + ) + + +def test_create_sk_ad_network_conversion_value_schema_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest, + dict, +]) +def test_delete_sk_ad_network_conversion_value_schema_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/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_sk_ad_network_conversion_value_schema(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_sk_ad_network_conversion_value_schema] = mock_rpc + + request = {} + client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_sk_ad_network_conversion_value_schema_rest_required_fields(request_type=analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_sk_ad_network_conversion_value_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_sk_ad_network_conversion_value_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + 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_sk_ad_network_conversion_value_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_sk_ad_network_conversion_value_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_sk_ad_network_conversion_value_schema_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_sk_ad_network_conversion_value_schema") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest.pb(analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest()) + 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 = analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_sk_ad_network_conversion_value_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_sk_ad_network_conversion_value_schema_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/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_sk_ad_network_conversion_value_schema(request) + + +def test_delete_sk_ad_network_conversion_value_schema_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/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_sk_ad_network_conversion_value_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}" % client.transport._host, args[1]) + + +def test_delete_sk_ad_network_conversion_value_schema_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_sk_ad_network_conversion_value_schema( + analytics_admin.DeleteSKAdNetworkConversionValueSchemaRequest(), + name='name_value', + ) + + +def test_delete_sk_ad_network_conversion_value_schema_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest, + dict, +]) +def test_update_sk_ad_network_conversion_value_schema_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'skadnetwork_conversion_value_schema': {'name': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3'}} + request_init["skadnetwork_conversion_value_schema"] = {'name': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3', 'postback_window_one': {'conversion_values': [{'display_name': 'display_name_value', 'fine_value': 1054, 'coarse_value': 1, 'event_mappings': [{'event_name': 'event_name_value', 'min_event_count': 1613, 'max_event_count': 1615, 'min_event_value': 0.16010000000000002, 'max_event_value': 0.1603}], 'lock_enabled': True}], 'postback_window_settings_enabled': True}, 'postback_window_two': {}, 'postback_window_three': {}, 'apply_conversion_values': 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 = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest.meta.fields["skadnetwork_conversion_value_schema"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["skadnetwork_conversion_value_schema"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["skadnetwork_conversion_value_schema"][field])): + del request_init["skadnetwork_conversion_value_schema"][field][i][subfield] + else: + del request_init["skadnetwork_conversion_value_schema"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.SKAdNetworkConversionValueSchema( + name='name_value', + apply_conversion_values=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 = resources.SKAdNetworkConversionValueSchema.pb(return_value) + 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_sk_ad_network_conversion_value_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SKAdNetworkConversionValueSchema) + assert response.name == 'name_value' + assert response.apply_conversion_values is True + +def test_update_sk_ad_network_conversion_value_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_sk_ad_network_conversion_value_schema in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_sk_ad_network_conversion_value_schema] = mock_rpc + + request = {} + client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sk_ad_network_conversion_value_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_sk_ad_network_conversion_value_schema_rest_required_fields(request_type=analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_sk_ad_network_conversion_value_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_sk_ad_network_conversion_value_schema._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.SKAdNetworkConversionValueSchema() + # 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 = resources.SKAdNetworkConversionValueSchema.pb(return_value) + 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_sk_ad_network_conversion_value_schema(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_sk_ad_network_conversion_value_schema_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_sk_ad_network_conversion_value_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("skadnetworkConversionValueSchema", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_sk_ad_network_conversion_value_schema_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_sk_ad_network_conversion_value_schema") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_sk_ad_network_conversion_value_schema") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest.pb(analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest()) + 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 = resources.SKAdNetworkConversionValueSchema.to_json(resources.SKAdNetworkConversionValueSchema()) + + request = analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.SKAdNetworkConversionValueSchema() + + client.update_sk_ad_network_conversion_value_schema(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_sk_ad_network_conversion_value_schema_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'skadnetwork_conversion_value_schema': {'name': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_sk_ad_network_conversion_value_schema(request) + + +def test_update_sk_ad_network_conversion_value_schema_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.SKAdNetworkConversionValueSchema() + + # get arguments that satisfy an http rule for this method + sample_request = {'skadnetwork_conversion_value_schema': {'name': 'properties/sample1/dataStreams/sample2/sKAdNetworkConversionValueSchema/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(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 = resources.SKAdNetworkConversionValueSchema.pb(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_sk_ad_network_conversion_value_schema(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{skadnetwork_conversion_value_schema.name=properties/*/dataStreams/*/sKAdNetworkConversionValueSchema/*}" % client.transport._host, args[1]) + + +def test_update_sk_ad_network_conversion_value_schema_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_sk_ad_network_conversion_value_schema( + analytics_admin.UpdateSKAdNetworkConversionValueSchemaRequest(), + skadnetwork_conversion_value_schema=resources.SKAdNetworkConversionValueSchema(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_sk_ad_network_conversion_value_schema_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListSKAdNetworkConversionValueSchemasRequest, + dict, +]) +def test_list_sk_ad_network_conversion_value_schemas_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + 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 = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb(return_value) + 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_sk_ad_network_conversion_value_schemas(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSKAdNetworkConversionValueSchemasPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_sk_ad_network_conversion_value_schemas_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_sk_ad_network_conversion_value_schemas in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_sk_ad_network_conversion_value_schemas] = mock_rpc + + request = {} + client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sk_ad_network_conversion_value_schemas(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_sk_ad_network_conversion_value_schemas_rest_required_fields(request_type=analytics_admin.ListSKAdNetworkConversionValueSchemasRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_sk_ad_network_conversion_value_schemas._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_sk_ad_network_conversion_value_schemas._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + # 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 = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb(return_value) + 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_sk_ad_network_conversion_value_schemas(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_sk_ad_network_conversion_value_schemas_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_sk_ad_network_conversion_value_schemas._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sk_ad_network_conversion_value_schemas_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_sk_ad_network_conversion_value_schemas") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_sk_ad_network_conversion_value_schemas") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest.pb(analytics_admin.ListSKAdNetworkConversionValueSchemasRequest()) + 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 = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.to_json(analytics_admin.ListSKAdNetworkConversionValueSchemasResponse()) + + request = analytics_admin.ListSKAdNetworkConversionValueSchemasRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + + client.list_sk_ad_network_conversion_value_schemas(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_sk_ad_network_conversion_value_schemas_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListSKAdNetworkConversionValueSchemasRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_sk_ad_network_conversion_value_schemas(request) + + +def test_list_sk_ad_network_conversion_value_schemas_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.pb(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_sk_ad_network_conversion_value_schemas(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=properties/*/dataStreams/*}/sKAdNetworkConversionValueSchema" % client.transport._host, args[1]) + + +def test_list_sk_ad_network_conversion_value_schemas_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_sk_ad_network_conversion_value_schemas( + analytics_admin.ListSKAdNetworkConversionValueSchemasRequest(), + parent='parent_value', + ) + + +def test_list_sk_ad_network_conversion_value_schemas_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='abc', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[], + next_page_token='def', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSKAdNetworkConversionValueSchemasResponse( + skadnetwork_conversion_value_schemas=[ + resources.SKAdNetworkConversionValueSchema(), + resources.SKAdNetworkConversionValueSchema(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListSKAdNetworkConversionValueSchemasResponse.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': 'properties/sample1/dataStreams/sample2'} + + pager = client.list_sk_ad_network_conversion_value_schemas(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SKAdNetworkConversionValueSchema) + for i in results) + + pages = list(client.list_sk_ad_network_conversion_value_schemas(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.SearchChangeHistoryEventsRequest, + dict, +]) +def test_search_change_history_events_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'account': 'accounts/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 = analytics_admin.SearchChangeHistoryEventsResponse( + 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 = analytics_admin.SearchChangeHistoryEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_change_history_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchChangeHistoryEventsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_search_change_history_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_change_history_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_change_history_events] = mock_rpc + + request = {} + client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_change_history_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_search_change_history_events_rest_required_fields(request_type=analytics_admin.SearchChangeHistoryEventsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["account"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_change_history_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["account"] = 'account_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_change_history_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "account" in jsonified_request + assert jsonified_request["account"] == 'account_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.SearchChangeHistoryEventsResponse() + # 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 = analytics_admin.SearchChangeHistoryEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search_change_history_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_change_history_events_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_change_history_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("account", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_change_history_events_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_search_change_history_events") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_search_change_history_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.SearchChangeHistoryEventsRequest.pb(analytics_admin.SearchChangeHistoryEventsRequest()) + 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 = analytics_admin.SearchChangeHistoryEventsResponse.to_json(analytics_admin.SearchChangeHistoryEventsResponse()) + + request = analytics_admin.SearchChangeHistoryEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.SearchChangeHistoryEventsResponse() + + client.search_change_history_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_change_history_events_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.SearchChangeHistoryEventsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'account': 'accounts/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.search_change_history_events(request) + + +def test_search_change_history_events_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.SearchChangeHistoryEventsResponse.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 = {'account': 'accounts/sample1'} + + pager = client.search_change_history_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ChangeHistoryEvent) + for i in results) + + pages = list(client.search_change_history_events(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetGoogleSignalsSettingsRequest, + dict, +]) +def test_get_google_signals_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/googleSignalsSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.GoogleSignalsSettings( + name='name_value', + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.GoogleSignalsSettings.pb(return_value) + 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_google_signals_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleSignalsSettings) + assert response.name == 'name_value' + assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED + assert response.consent == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED + +def test_get_google_signals_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_google_signals_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_google_signals_settings] = mock_rpc + + request = {} + client.get_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_google_signals_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_google_signals_settings_rest_required_fields(request_type=analytics_admin.GetGoogleSignalsSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_signals_settings._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_google_signals_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.GoogleSignalsSettings() + # 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 = resources.GoogleSignalsSettings.pb(return_value) + 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_google_signals_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_google_signals_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_google_signals_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_google_signals_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_google_signals_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_google_signals_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetGoogleSignalsSettingsRequest.pb(analytics_admin.GetGoogleSignalsSettingsRequest()) + 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 = resources.GoogleSignalsSettings.to_json(resources.GoogleSignalsSettings()) + + request = analytics_admin.GetGoogleSignalsSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.GoogleSignalsSettings() + + client.get_google_signals_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_google_signals_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetGoogleSignalsSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/googleSignalsSettings'} + 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_google_signals_settings(request) + + +def test_get_google_signals_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.GoogleSignalsSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/googleSignalsSettings'} + + # 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 = resources.GoogleSignalsSettings.pb(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_google_signals_settings(**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/v1alpha/{name=properties/*/googleSignalsSettings}" % client.transport._host, args[1]) + + +def test_get_google_signals_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_signals_settings( + analytics_admin.GetGoogleSignalsSettingsRequest(), + name='name_value', + ) + + +def test_get_google_signals_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateGoogleSignalsSettingsRequest, + dict, +]) +def test_update_google_signals_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'google_signals_settings': {'name': 'properties/sample1/googleSignalsSettings'}} + request_init["google_signals_settings"] = {'name': 'properties/sample1/googleSignalsSettings', 'state': 1, 'consent': 2} + # 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 = analytics_admin.UpdateGoogleSignalsSettingsRequest.meta.fields["google_signals_settings"] + + 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["google_signals_settings"].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["google_signals_settings"][field])): + del request_init["google_signals_settings"][field][i][subfield] + else: + del request_init["google_signals_settings"][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 = resources.GoogleSignalsSettings( + name='name_value', + state=resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED, + consent=resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.GoogleSignalsSettings.pb(return_value) + 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_google_signals_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleSignalsSettings) + assert response.name == 'name_value' + assert response.state == resources.GoogleSignalsState.GOOGLE_SIGNALS_ENABLED + assert response.consent == resources.GoogleSignalsConsent.GOOGLE_SIGNALS_CONSENT_CONSENTED + +def test_update_google_signals_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_google_signals_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_google_signals_settings] = mock_rpc + + request = {} + client.update_google_signals_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_google_signals_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_google_signals_settings_rest_required_fields(request_type=analytics_admin.UpdateGoogleSignalsSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_signals_settings._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_google_signals_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.GoogleSignalsSettings() + # 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 = resources.GoogleSignalsSettings.pb(return_value) + 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_google_signals_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_google_signals_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_google_signals_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("googleSignalsSettings", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_google_signals_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_google_signals_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_google_signals_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateGoogleSignalsSettingsRequest.pb(analytics_admin.UpdateGoogleSignalsSettingsRequest()) + 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 = resources.GoogleSignalsSettings.to_json(resources.GoogleSignalsSettings()) + + request = analytics_admin.UpdateGoogleSignalsSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.GoogleSignalsSettings() + + client.update_google_signals_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_google_signals_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateGoogleSignalsSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'google_signals_settings': {'name': 'properties/sample1/googleSignalsSettings'}} + 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_google_signals_settings(request) + + +def test_update_google_signals_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.GoogleSignalsSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'google_signals_settings': {'name': 'properties/sample1/googleSignalsSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + google_signals_settings=resources.GoogleSignalsSettings(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 = resources.GoogleSignalsSettings.pb(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_google_signals_settings(**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/v1alpha/{google_signals_settings.name=properties/*/googleSignalsSettings}" % client.transport._host, args[1]) + + +def test_update_google_signals_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_signals_settings( + analytics_admin.UpdateGoogleSignalsSettingsRequest(), + google_signals_settings=resources.GoogleSignalsSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_google_signals_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateConversionEventRequest, + dict, +]) +def test_create_conversion_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["conversion_event"] = {'name': 'name_value', 'event_name': 'event_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'deletable': True, 'custom': True, 'counting_method': 1, 'default_conversion_value': {'value': 0.541, 'currency_code': 'currency_code_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 = analytics_admin.CreateConversionEventRequest.meta.fields["conversion_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["conversion_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["conversion_event"][field])): + del request_init["conversion_event"][field][i][subfield] + else: + del request_init["conversion_event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + +def test_create_conversion_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_conversion_event] = mock_rpc + + request = {} + client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_conversion_event_rest_required_fields(request_type=analytics_admin.CreateConversionEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_event._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_conversion_event._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent() + # 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 = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_conversion_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("conversionEvent", "parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_conversion_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_conversion_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_conversion_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateConversionEventRequest.pb(analytics_admin.CreateConversionEventRequest()) + 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 = resources.ConversionEvent.to_json(resources.ConversionEvent()) + + request = analytics_admin.CreateConversionEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ConversionEvent() + + client.create_conversion_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_conversion_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateConversionEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_conversion_event(request) + + +def test_create_conversion_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.ConversionEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + conversion_event=resources.ConversionEvent(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 = resources.ConversionEvent.pb(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_conversion_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=properties/*}/conversionEvents" % client.transport._host, args[1]) + + +def test_create_conversion_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_event( + analytics_admin.CreateConversionEventRequest(), + parent='parent_value', + conversion_event=resources.ConversionEvent(name='name_value'), + ) + + +def test_create_conversion_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateConversionEventRequest, + dict, +]) +def test_update_conversion_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'conversion_event': {'name': 'properties/sample1/conversionEvents/sample2'}} + request_init["conversion_event"] = {'name': 'properties/sample1/conversionEvents/sample2', 'event_name': 'event_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'deletable': True, 'custom': True, 'counting_method': 1, 'default_conversion_value': {'value': 0.541, 'currency_code': 'currency_code_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 = analytics_admin.UpdateConversionEventRequest.meta.fields["conversion_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["conversion_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["conversion_event"][field])): + del request_init["conversion_event"][field][i][subfield] + else: + del request_init["conversion_event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + +def test_update_conversion_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_conversion_event] = mock_rpc + + request = {} + client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_conversion_event_rest_required_fields(request_type=analytics_admin.UpdateConversionEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversion_event._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent() + # 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 = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_conversion_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("conversionEvent", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_conversion_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_conversion_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_conversion_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateConversionEventRequest.pb(analytics_admin.UpdateConversionEventRequest()) + 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 = resources.ConversionEvent.to_json(resources.ConversionEvent()) + + request = analytics_admin.UpdateConversionEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ConversionEvent() + + client.update_conversion_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_conversion_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateConversionEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'conversion_event': {'name': 'properties/sample1/conversionEvents/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_conversion_event(request) + + +def test_update_conversion_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.ConversionEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'conversion_event': {'name': 'properties/sample1/conversionEvents/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + conversion_event=resources.ConversionEvent(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 = resources.ConversionEvent.pb(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_conversion_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{conversion_event.name=properties/*/conversionEvents/*}" % client.transport._host, args[1]) + + +def test_update_conversion_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_event( + analytics_admin.UpdateConversionEventRequest(), + conversion_event=resources.ConversionEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_conversion_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetConversionEventRequest, + dict, +]) +def test_get_conversion_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/conversionEvents/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 = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + +def test_get_conversion_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_conversion_event] = mock_rpc + + request = {} + client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_conversion_event_rest_required_fields(request_type=analytics_admin.GetConversionEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent() + # 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 = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_conversion_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_conversion_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_conversion_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_conversion_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetConversionEventRequest.pb(analytics_admin.GetConversionEventRequest()) + 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 = resources.ConversionEvent.to_json(resources.ConversionEvent()) + + request = analytics_admin.GetConversionEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ConversionEvent() + + client.get_conversion_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_conversion_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetConversionEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/conversionEvents/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_conversion_event(request) + + +def test_get_conversion_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.ConversionEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/conversionEvents/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 = resources.ConversionEvent.pb(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_conversion_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=properties/*/conversionEvents/*}" % client.transport._host, args[1]) + + +def test_get_conversion_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_event( + analytics_admin.GetConversionEventRequest(), + name='name_value', + ) + + +def test_get_conversion_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteConversionEventRequest, + dict, +]) +def test_delete_conversion_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/conversionEvents/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_conversion_event(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_conversion_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_conversion_event] = mock_rpc + + request = {} + client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_conversion_event_rest_required_fields(request_type=analytics_admin.DeleteConversionEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + 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_conversion_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_conversion_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_conversion_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_conversion_event") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteConversionEventRequest.pb(analytics_admin.DeleteConversionEventRequest()) + 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 = analytics_admin.DeleteConversionEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_conversion_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_conversion_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteConversionEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/conversionEvents/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_conversion_event(request) + + +def test_delete_conversion_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/conversionEvents/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_conversion_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=properties/*/conversionEvents/*}" % client.transport._host, args[1]) + + +def test_delete_conversion_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_event( + analytics_admin.DeleteConversionEventRequest(), + name='name_value', + ) + + +def test_delete_conversion_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListConversionEventsRequest, + dict, +]) +def test_list_conversion_events_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListConversionEventsResponse( + 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 = analytics_admin.ListConversionEventsResponse.pb(return_value) + 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_conversion_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversionEventsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_conversion_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_conversion_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_conversion_events] = mock_rpc + + request = {} + client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conversion_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_conversion_events_rest_required_fields(request_type=analytics_admin.ListConversionEventsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversion_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListConversionEventsResponse() + # 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 = analytics_admin.ListConversionEventsResponse.pb(return_value) + 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_conversion_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_conversion_events_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_conversion_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_conversion_events_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_conversion_events") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_conversion_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListConversionEventsRequest.pb(analytics_admin.ListConversionEventsRequest()) + 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 = analytics_admin.ListConversionEventsResponse.to_json(analytics_admin.ListConversionEventsResponse()) + + request = analytics_admin.ListConversionEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListConversionEventsResponse() + + client.list_conversion_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_conversion_events_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListConversionEventsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_conversion_events(request) + + +def test_list_conversion_events_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListConversionEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListConversionEventsResponse.pb(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_conversion_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=properties/*}/conversionEvents" % client.transport._host, args[1]) + + +def test_list_conversion_events_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_events( + analytics_admin.ListConversionEventsRequest(), + parent='parent_value', + ) + + +def test_list_conversion_events_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListConversionEventsResponse.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': 'properties/sample1'} + + pager = client.list_conversion_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ConversionEvent) + for i in results) + + pages = list(client.list_conversion_events(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateKeyEventRequest, + dict, +]) +def test_create_key_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["key_event"] = {'name': 'name_value', 'event_name': 'event_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'deletable': True, 'custom': True, 'counting_method': 1, 'default_value': {'numeric_value': 0.1391, 'currency_code': 'currency_code_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 = analytics_admin.CreateKeyEventRequest.meta.fields["key_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["key_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["key_event"][field])): + del request_init["key_event"][field][i][subfield] + else: + del request_init["key_event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + +def test_create_key_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_key_event] = mock_rpc + + request = {} + client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_key_event_rest_required_fields(request_type=analytics_admin.CreateKeyEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_event._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_key_event._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent() + # 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 = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_key_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("keyEvent", "parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_key_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_key_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_key_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateKeyEventRequest.pb(analytics_admin.CreateKeyEventRequest()) + 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 = resources.KeyEvent.to_json(resources.KeyEvent()) + + request = analytics_admin.CreateKeyEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyEvent() + + client.create_key_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_key_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateKeyEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_key_event(request) + + +def test_create_key_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.KeyEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + key_event=resources.KeyEvent(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 = resources.KeyEvent.pb(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_key_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=properties/*}/keyEvents" % client.transport._host, args[1]) + + +def test_create_key_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_event( + analytics_admin.CreateKeyEventRequest(), + parent='parent_value', + key_event=resources.KeyEvent(name='name_value'), + ) + + +def test_create_key_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateKeyEventRequest, + dict, +]) +def test_update_key_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'key_event': {'name': 'properties/sample1/keyEvents/sample2'}} + request_init["key_event"] = {'name': 'properties/sample1/keyEvents/sample2', 'event_name': 'event_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'deletable': True, 'custom': True, 'counting_method': 1, 'default_value': {'numeric_value': 0.1391, 'currency_code': 'currency_code_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 = analytics_admin.UpdateKeyEventRequest.meta.fields["key_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["key_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["key_event"][field])): + del request_init["key_event"][field][i][subfield] + else: + del request_init["key_event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + +def test_update_key_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_key_event] = mock_rpc + + request = {} + client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_key_event_rest_required_fields(request_type=analytics_admin.UpdateKeyEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_key_event._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent() + # 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 = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_key_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("keyEvent", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_key_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_key_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_key_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateKeyEventRequest.pb(analytics_admin.UpdateKeyEventRequest()) + 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 = resources.KeyEvent.to_json(resources.KeyEvent()) + + request = analytics_admin.UpdateKeyEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyEvent() + + client.update_key_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_key_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateKeyEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'key_event': {'name': 'properties/sample1/keyEvents/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_key_event(request) + + +def test_update_key_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.KeyEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'key_event': {'name': 'properties/sample1/keyEvents/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + key_event=resources.KeyEvent(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 = resources.KeyEvent.pb(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_key_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{key_event.name=properties/*/keyEvents/*}" % client.transport._host, args[1]) + + +def test_update_key_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_event( + analytics_admin.UpdateKeyEventRequest(), + key_event=resources.KeyEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_key_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetKeyEventRequest, + dict, +]) +def test_get_key_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/keyEvents/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 = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + +def test_get_key_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_key_event] = mock_rpc + + request = {} + client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_key_event_rest_required_fields(request_type=analytics_admin.GetKeyEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent() + # 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 = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_key_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_key_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_key_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_key_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetKeyEventRequest.pb(analytics_admin.GetKeyEventRequest()) + 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 = resources.KeyEvent.to_json(resources.KeyEvent()) + + request = analytics_admin.GetKeyEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyEvent() + + client.get_key_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_key_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetKeyEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/keyEvents/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_key_event(request) + + +def test_get_key_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.KeyEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/keyEvents/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 = resources.KeyEvent.pb(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_key_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=properties/*/keyEvents/*}" % client.transport._host, args[1]) + + +def test_get_key_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_event( + analytics_admin.GetKeyEventRequest(), + name='name_value', + ) + + +def test_get_key_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteKeyEventRequest, + dict, +]) +def test_delete_key_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/keyEvents/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_key_event(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_key_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_key_event] = mock_rpc + + request = {} + client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_key_event_rest_required_fields(request_type=analytics_admin.DeleteKeyEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + 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_key_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_key_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_key_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_key_event") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteKeyEventRequest.pb(analytics_admin.DeleteKeyEventRequest()) + 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 = analytics_admin.DeleteKeyEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_key_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_key_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteKeyEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/keyEvents/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_key_event(request) + + +def test_delete_key_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/keyEvents/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_key_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=properties/*/keyEvents/*}" % client.transport._host, args[1]) + + +def test_delete_key_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_event( + analytics_admin.DeleteKeyEventRequest(), + name='name_value', + ) + + +def test_delete_key_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListKeyEventsRequest, + dict, +]) +def test_list_key_events_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListKeyEventsResponse( + 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 = analytics_admin.ListKeyEventsResponse.pb(return_value) + 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_key_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyEventsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_key_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_key_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_key_events] = mock_rpc + + request = {} + client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_key_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_key_events_rest_required_fields(request_type=analytics_admin.ListKeyEventsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListKeyEventsResponse() + # 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 = analytics_admin.ListKeyEventsResponse.pb(return_value) + 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_key_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_key_events_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_key_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_key_events_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_key_events") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_key_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListKeyEventsRequest.pb(analytics_admin.ListKeyEventsRequest()) + 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 = analytics_admin.ListKeyEventsResponse.to_json(analytics_admin.ListKeyEventsResponse()) + + request = analytics_admin.ListKeyEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListKeyEventsResponse() + + client.list_key_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_key_events_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListKeyEventsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_key_events(request) + + +def test_list_key_events_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListKeyEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListKeyEventsResponse.pb(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_key_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=properties/*}/keyEvents" % client.transport._host, args[1]) + + +def test_list_key_events_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_events( + analytics_admin.ListKeyEventsRequest(), + parent='parent_value', + ) + + +def test_list_key_events_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListKeyEventsResponse.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': 'properties/sample1'} + + pager = client.list_key_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.KeyEvent) + for i in results) + + pages = list(client.list_key_events(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest, + dict, +]) +def test_get_display_video360_advertiser_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinks/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 = resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_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 = resources.DisplayVideo360AdvertiserLink.pb(return_value) + 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_display_video360_advertiser_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + +def test_get_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_display_video360_advertiser_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_display_video360_advertiser_link] = mock_rpc + + request = {} + client.get_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_display_video360_advertiser_link_rest_required_fields(request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_display_video360_advertiser_link._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_display_video360_advertiser_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DisplayVideo360AdvertiserLink() + # 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 = resources.DisplayVideo360AdvertiserLink.pb(return_value) + 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_display_video360_advertiser_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_display_video360_advertiser_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_display_video360_advertiser_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_display_video360_advertiser_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_display_video360_advertiser_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_display_video360_advertiser_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest.pb(analytics_admin.GetDisplayVideo360AdvertiserLinkRequest()) + 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 = resources.DisplayVideo360AdvertiserLink.to_json(resources.DisplayVideo360AdvertiserLink()) + + request = analytics_admin.GetDisplayVideo360AdvertiserLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DisplayVideo360AdvertiserLink() + + client.get_display_video360_advertiser_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_display_video360_advertiser_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinks/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_display_video360_advertiser_link(request) + + +def test_get_display_video360_advertiser_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DisplayVideo360AdvertiserLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/displayVideo360AdvertiserLinks/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 = resources.DisplayVideo360AdvertiserLink.pb(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_display_video360_advertiser_link(**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/v1alpha/{name=properties/*/displayVideo360AdvertiserLinks/*}" % client.transport._host, args[1]) + + +def test_get_display_video360_advertiser_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link( + analytics_admin.GetDisplayVideo360AdvertiserLinkRequest(), + name='name_value', + ) + + +def test_get_display_video360_advertiser_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, + dict, +]) +def test_list_display_video360_advertiser_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + 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 = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb(return_value) + 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_display_video360_advertiser_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinksPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_display_video360_advertiser_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_display_video360_advertiser_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_display_video360_advertiser_links] = mock_rpc + + request = {} + client.list_display_video360_advertiser_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_display_video360_advertiser_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_display_video360_advertiser_links_rest_required_fields(request_type=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_display_video360_advertiser_links._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_display_video360_advertiser_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + # 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 = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb(return_value) + 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_display_video360_advertiser_links(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_display_video360_advertiser_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_display_video360_advertiser_links._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_display_video360_advertiser_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_display_video360_advertiser_links") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_display_video360_advertiser_links") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest.pb(analytics_admin.ListDisplayVideo360AdvertiserLinksRequest()) + 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 = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.to_json(analytics_admin.ListDisplayVideo360AdvertiserLinksResponse()) + + request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + + client.list_display_video360_advertiser_links(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_display_video360_advertiser_links_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListDisplayVideo360AdvertiserLinksRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_display_video360_advertiser_links(request) + + +def test_list_display_video360_advertiser_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.pb(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_display_video360_advertiser_links(**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/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinks" % client.transport._host, args[1]) + + +def test_list_display_video360_advertiser_links_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_links( + analytics_admin.ListDisplayVideo360AdvertiserLinksRequest(), + parent='parent_value', + ) + + +def test_list_display_video360_advertiser_links_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinksResponse( + display_video_360_advertiser_links=[ + resources.DisplayVideo360AdvertiserLink(), + resources.DisplayVideo360AdvertiserLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListDisplayVideo360AdvertiserLinksResponse.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': 'properties/sample1'} + + pager = client.list_display_video360_advertiser_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DisplayVideo360AdvertiserLink) + for i in results) + + pages = list(client.list_display_video360_advertiser_links(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", [ + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest, + dict, +]) +def test_create_display_video360_advertiser_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["display_video_360_advertiser_link"] = {'name': 'name_value', 'advertiser_id': 'advertiser_id_value', 'advertiser_display_name': 'advertiser_display_name_value', 'ads_personalization_enabled': {'value': True}, 'campaign_data_sharing_enabled': {}, 'cost_data_sharing_enabled': {}} + # 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 = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest.meta.fields["display_video_360_advertiser_link"] + + 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["display_video_360_advertiser_link"].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["display_video_360_advertiser_link"][field])): + del request_init["display_video_360_advertiser_link"][field][i][subfield] + else: + del request_init["display_video_360_advertiser_link"][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 = resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_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 = resources.DisplayVideo360AdvertiserLink.pb(return_value) + 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_display_video360_advertiser_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + +def test_create_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_display_video360_advertiser_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_display_video360_advertiser_link] = mock_rpc + + request = {} + client.create_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_display_video360_advertiser_link_rest_required_fields(request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_display_video360_advertiser_link._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_display_video360_advertiser_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DisplayVideo360AdvertiserLink() + # 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 = resources.DisplayVideo360AdvertiserLink.pb(return_value) + 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_display_video360_advertiser_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_display_video360_advertiser_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_display_video360_advertiser_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "displayVideo360AdvertiserLink", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_display_video360_advertiser_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_display_video360_advertiser_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_display_video360_advertiser_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest.pb(analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest()) + 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 = resources.DisplayVideo360AdvertiserLink.to_json(resources.DisplayVideo360AdvertiserLink()) + + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DisplayVideo360AdvertiserLink() + + client.create_display_video360_advertiser_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_display_video360_advertiser_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_display_video360_advertiser_link(request) + + +def test_create_display_video360_advertiser_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DisplayVideo360AdvertiserLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(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 = resources.DisplayVideo360AdvertiserLink.pb(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_display_video360_advertiser_link(**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/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinks" % client.transport._host, args[1]) + + +def test_create_display_video360_advertiser_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link( + analytics_admin.CreateDisplayVideo360AdvertiserLinkRequest(), + parent='parent_value', + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(name='name_value'), + ) + + +def test_create_display_video360_advertiser_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest, + dict, +]) +def test_delete_display_video360_advertiser_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinks/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_display_video360_advertiser_link(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_display_video360_advertiser_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_display_video360_advertiser_link] = mock_rpc + + request = {} + client.delete_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_display_video360_advertiser_link_rest_required_fields(request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_display_video360_advertiser_link._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_display_video360_advertiser_link._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 = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_display_video360_advertiser_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_display_video360_advertiser_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_display_video360_advertiser_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_display_video360_advertiser_link") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest.pb(analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest()) + 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 = analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_display_video360_advertiser_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_display_video360_advertiser_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinks/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_display_video360_advertiser_link(request) + + +def test_delete_display_video360_advertiser_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/displayVideo360AdvertiserLinks/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_display_video360_advertiser_link(**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/v1alpha/{name=properties/*/displayVideo360AdvertiserLinks/*}" % client.transport._host, args[1]) + + +def test_delete_display_video360_advertiser_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkRequest(), + name='name_value', + ) + + +def test_delete_display_video360_advertiser_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest, + dict, +]) +def test_update_display_video360_advertiser_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'display_video_360_advertiser_link': {'name': 'properties/sample1/displayVideo360AdvertiserLinks/sample2'}} + request_init["display_video_360_advertiser_link"] = {'name': 'properties/sample1/displayVideo360AdvertiserLinks/sample2', 'advertiser_id': 'advertiser_id_value', 'advertiser_display_name': 'advertiser_display_name_value', 'ads_personalization_enabled': {'value': True}, 'campaign_data_sharing_enabled': {}, 'cost_data_sharing_enabled': {}} + # 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 = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest.meta.fields["display_video_360_advertiser_link"] + + 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["display_video_360_advertiser_link"].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["display_video_360_advertiser_link"][field])): + del request_init["display_video_360_advertiser_link"][field][i][subfield] + else: + del request_init["display_video_360_advertiser_link"][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 = resources.DisplayVideo360AdvertiserLink( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_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 = resources.DisplayVideo360AdvertiserLink.pb(return_value) + 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_display_video360_advertiser_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLink) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + +def test_update_display_video360_advertiser_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_display_video360_advertiser_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_display_video360_advertiser_link] = mock_rpc + + request = {} + client.update_display_video360_advertiser_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_display_video360_advertiser_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_display_video360_advertiser_link_rest_required_fields(request_type=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_display_video360_advertiser_link._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_display_video360_advertiser_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DisplayVideo360AdvertiserLink() + # 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 = resources.DisplayVideo360AdvertiserLink.pb(return_value) + 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_display_video360_advertiser_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_display_video360_advertiser_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_display_video360_advertiser_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_display_video360_advertiser_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_display_video360_advertiser_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_display_video360_advertiser_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest.pb(analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest()) + 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 = resources.DisplayVideo360AdvertiserLink.to_json(resources.DisplayVideo360AdvertiserLink()) + + request = analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DisplayVideo360AdvertiserLink() + + client.update_display_video360_advertiser_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_display_video360_advertiser_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'display_video_360_advertiser_link': {'name': 'properties/sample1/displayVideo360AdvertiserLinks/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_display_video360_advertiser_link(request) + + +def test_update_display_video360_advertiser_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DisplayVideo360AdvertiserLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'display_video_360_advertiser_link': {'name': 'properties/sample1/displayVideo360AdvertiserLinks/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(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 = resources.DisplayVideo360AdvertiserLink.pb(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_display_video360_advertiser_link(**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/v1alpha/{display_video_360_advertiser_link.name=properties/*/displayVideo360AdvertiserLinks/*}" % client.transport._host, args[1]) + + +def test_update_display_video360_advertiser_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link( + analytics_admin.UpdateDisplayVideo360AdvertiserLinkRequest(), + display_video_360_advertiser_link=resources.DisplayVideo360AdvertiserLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_display_video360_advertiser_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_get_display_video360_advertiser_link_proposal_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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 = resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_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 = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + 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_display_video360_advertiser_link_proposal(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + assert response.validation_email == 'validation_email_value' + +def test_get_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_display_video360_advertiser_link_proposal] = mock_rpc + + request = {} + client.get_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_display_video360_advertiser_link_proposal_rest_required_fields(request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_display_video360_advertiser_link_proposal._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_display_video360_advertiser_link_proposal._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DisplayVideo360AdvertiserLinkProposal() + # 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 = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + 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_display_video360_advertiser_link_proposal(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_display_video360_advertiser_link_proposal_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_display_video360_advertiser_link_proposal._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_display_video360_advertiser_link_proposal_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_display_video360_advertiser_link_proposal") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_display_video360_advertiser_link_proposal") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest.pb(analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest()) + 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 = resources.DisplayVideo360AdvertiserLinkProposal.to_json(resources.DisplayVideo360AdvertiserLinkProposal()) + + request = analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + + client.get_display_video360_advertiser_link_proposal(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_display_video360_advertiser_link_proposal_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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_display_video360_advertiser_link_proposal(request) + + +def test_get_display_video360_advertiser_link_proposal_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DisplayVideo360AdvertiserLinkProposal() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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 = resources.DisplayVideo360AdvertiserLinkProposal.pb(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_display_video360_advertiser_link_proposal(**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/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}" % client.transport._host, args[1]) + + +def test_get_display_video360_advertiser_link_proposal_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link_proposal( + analytics_admin.GetDisplayVideo360AdvertiserLinkProposalRequest(), + name='name_value', + ) + + +def test_get_display_video360_advertiser_link_proposal_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest, + dict, +]) +def test_list_display_video360_advertiser_link_proposals_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + 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 = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb(return_value) + 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_display_video360_advertiser_link_proposals(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDisplayVideo360AdvertiserLinkProposalsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_display_video360_advertiser_link_proposals_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_display_video360_advertiser_link_proposals in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_display_video360_advertiser_link_proposals] = mock_rpc + + request = {} + client.list_display_video360_advertiser_link_proposals(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_display_video360_advertiser_link_proposals(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_display_video360_advertiser_link_proposals_rest_required_fields(request_type=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_display_video360_advertiser_link_proposals._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_display_video360_advertiser_link_proposals._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + # 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 = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb(return_value) + 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_display_video360_advertiser_link_proposals(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_display_video360_advertiser_link_proposals_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_display_video360_advertiser_link_proposals._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_display_video360_advertiser_link_proposals_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_display_video360_advertiser_link_proposals") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_display_video360_advertiser_link_proposals") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest.pb(analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest()) + 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 = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.to_json(analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse()) + + request = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + + client.list_display_video360_advertiser_link_proposals(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_display_video360_advertiser_link_proposals_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_display_video360_advertiser_link_proposals(request) + + +def test_list_display_video360_advertiser_link_proposals_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.pb(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_display_video360_advertiser_link_proposals(**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/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinkProposals" % client.transport._host, args[1]) + + +def test_list_display_video360_advertiser_link_proposals_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link_proposals( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsRequest(), + parent='parent_value', + ) + + +def test_list_display_video360_advertiser_link_proposals_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='abc', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[], + next_page_token='def', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse( + display_video_360_advertiser_link_proposals=[ + resources.DisplayVideo360AdvertiserLinkProposal(), + resources.DisplayVideo360AdvertiserLinkProposal(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListDisplayVideo360AdvertiserLinkProposalsResponse.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': 'properties/sample1'} + + pager = client.list_display_video360_advertiser_link_proposals(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DisplayVideo360AdvertiserLinkProposal) + for i in results) + + pages = list(client.list_display_video360_advertiser_link_proposals(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", [ + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_create_display_video360_advertiser_link_proposal_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["display_video_360_advertiser_link_proposal"] = {'name': 'name_value', 'advertiser_id': 'advertiser_id_value', 'link_proposal_status_details': {'link_proposal_initiating_product': 1, 'requestor_email': 'requestor_email_value', 'link_proposal_state': 1}, 'advertiser_display_name': 'advertiser_display_name_value', 'validation_email': 'validation_email_value', 'ads_personalization_enabled': {'value': True}, 'campaign_data_sharing_enabled': {}, 'cost_data_sharing_enabled': {}} + # 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 = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest.meta.fields["display_video_360_advertiser_link_proposal"] + + 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["display_video_360_advertiser_link_proposal"].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["display_video_360_advertiser_link_proposal"][field])): + del request_init["display_video_360_advertiser_link_proposal"][field][i][subfield] + else: + del request_init["display_video_360_advertiser_link_proposal"][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 = resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_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 = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + 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_display_video360_advertiser_link_proposal(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + assert response.validation_email == 'validation_email_value' + +def test_create_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_display_video360_advertiser_link_proposal] = mock_rpc + + request = {} + client.create_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_display_video360_advertiser_link_proposal_rest_required_fields(request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_display_video360_advertiser_link_proposal._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_display_video360_advertiser_link_proposal._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DisplayVideo360AdvertiserLinkProposal() + # 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 = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + 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_display_video360_advertiser_link_proposal(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_display_video360_advertiser_link_proposal_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_display_video360_advertiser_link_proposal._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "displayVideo360AdvertiserLinkProposal", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_display_video360_advertiser_link_proposal_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_display_video360_advertiser_link_proposal") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_display_video360_advertiser_link_proposal") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest.pb(analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest()) + 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 = resources.DisplayVideo360AdvertiserLinkProposal.to_json(resources.DisplayVideo360AdvertiserLinkProposal()) + + request = analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + + client.create_display_video360_advertiser_link_proposal(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_display_video360_advertiser_link_proposal_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_display_video360_advertiser_link_proposal(request) + + +def test_create_display_video360_advertiser_link_proposal_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DisplayVideo360AdvertiserLinkProposal() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal(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 = resources.DisplayVideo360AdvertiserLinkProposal.pb(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_display_video360_advertiser_link_proposal(**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/v1alpha/{parent=properties/*}/displayVideo360AdvertiserLinkProposals" % client.transport._host, args[1]) + + +def test_create_display_video360_advertiser_link_proposal_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link_proposal( + analytics_admin.CreateDisplayVideo360AdvertiserLinkProposalRequest(), + parent='parent_value', + display_video_360_advertiser_link_proposal=resources.DisplayVideo360AdvertiserLinkProposal(name='name_value'), + ) + + +def test_create_display_video360_advertiser_link_proposal_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_delete_display_video360_advertiser_link_proposal_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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_display_video360_advertiser_link_proposal(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_display_video360_advertiser_link_proposal] = mock_rpc + + request = {} + client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_display_video360_advertiser_link_proposal_rest_required_fields(request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_display_video360_advertiser_link_proposal._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_display_video360_advertiser_link_proposal._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 = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link_proposal(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_display_video360_advertiser_link_proposal_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_display_video360_advertiser_link_proposal._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_display_video360_advertiser_link_proposal_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_display_video360_advertiser_link_proposal") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest.pb(analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest()) + 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 = analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_display_video360_advertiser_link_proposal(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_display_video360_advertiser_link_proposal_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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_display_video360_advertiser_link_proposal(request) + + +def test_delete_display_video360_advertiser_link_proposal_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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_display_video360_advertiser_link_proposal(**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/v1alpha/{name=properties/*/displayVideo360AdvertiserLinkProposals/*}" % client.transport._host, args[1]) + + +def test_delete_display_video360_advertiser_link_proposal_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_display_video360_advertiser_link_proposal( + analytics_admin.DeleteDisplayVideo360AdvertiserLinkProposalRequest(), + name='name_value', + ) + + +def test_delete_display_video360_advertiser_link_proposal_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_approve_display_video360_advertiser_link_proposal_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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 = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse) + +def test_approve_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.approve_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.approve_display_video360_advertiser_link_proposal] = mock_rpc + + request = {} + client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.approve_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_approve_display_video360_advertiser_link_proposal_rest_required_fields(request_type=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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()).approve_display_video360_advertiser_link_proposal._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()).approve_display_video360_advertiser_link_proposal._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + # 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 = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.approve_display_video360_advertiser_link_proposal(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_approve_display_video360_advertiser_link_proposal_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.approve_display_video360_advertiser_link_proposal._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_approve_display_video360_advertiser_link_proposal_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_approve_display_video360_advertiser_link_proposal") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_approve_display_video360_advertiser_link_proposal") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest.pb(analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest()) + 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 = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse.to_json(analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse()) + + request = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalResponse() + + client.approve_display_video360_advertiser_link_proposal(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_approve_display_video360_advertiser_link_proposal_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ApproveDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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.approve_display_video360_advertiser_link_proposal(request) + + +def test_approve_display_video360_advertiser_link_proposal_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest, + dict, +]) +def test_cancel_display_video360_advertiser_link_proposal_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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 = resources.DisplayVideo360AdvertiserLinkProposal( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_name_value', + validation_email='validation_email_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 = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DisplayVideo360AdvertiserLinkProposal) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + assert response.validation_email == 'validation_email_value' + +def test_cancel_display_video360_advertiser_link_proposal_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.cancel_display_video360_advertiser_link_proposal in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.cancel_display_video360_advertiser_link_proposal] = mock_rpc + + request = {} + client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.cancel_display_video360_advertiser_link_proposal(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_cancel_display_video360_advertiser_link_proposal_rest_required_fields(request_type=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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()).cancel_display_video360_advertiser_link_proposal._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()).cancel_display_video360_advertiser_link_proposal._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DisplayVideo360AdvertiserLinkProposal() + # 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 = resources.DisplayVideo360AdvertiserLinkProposal.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_display_video360_advertiser_link_proposal(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_cancel_display_video360_advertiser_link_proposal_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.cancel_display_video360_advertiser_link_proposal._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_cancel_display_video360_advertiser_link_proposal_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_cancel_display_video360_advertiser_link_proposal") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_cancel_display_video360_advertiser_link_proposal") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest.pb(analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest()) + 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 = resources.DisplayVideo360AdvertiserLinkProposal.to_json(resources.DisplayVideo360AdvertiserLinkProposal()) + + request = analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DisplayVideo360AdvertiserLinkProposal() + + client.cancel_display_video360_advertiser_link_proposal(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_cancel_display_video360_advertiser_link_proposal_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CancelDisplayVideo360AdvertiserLinkProposalRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/displayVideo360AdvertiserLinkProposals/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.cancel_display_video360_advertiser_link_proposal(request) + + +def test_cancel_display_video360_advertiser_link_proposal_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateCustomDimensionRequest, + dict, +]) +def test_create_custom_dimension_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["custom_dimension"] = {'name': 'name_value', 'parameter_name': 'parameter_name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'scope': 1, 'disallow_ads_personalization': 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 = analytics_admin.CreateCustomDimensionRequest.meta.fields["custom_dimension"] + + 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["custom_dimension"].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["custom_dimension"][field])): + del request_init["custom_dimension"][field][i][subfield] + else: + del request_init["custom_dimension"][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 = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + +def test_create_custom_dimension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_custom_dimension] = mock_rpc + + request = {} + client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_custom_dimension_rest_required_fields(request_type=analytics_admin.CreateCustomDimensionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_dimension._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_custom_dimension._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomDimension() + # 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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_custom_dimension_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "customDimension", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_custom_dimension_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_custom_dimension") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_custom_dimension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateCustomDimensionRequest.pb(analytics_admin.CreateCustomDimensionRequest()) + 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 = resources.CustomDimension.to_json(resources.CustomDimension()) + + request = analytics_admin.CreateCustomDimensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomDimension() + + client.create_custom_dimension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_custom_dimension_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateCustomDimensionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_custom_dimension(request) + + +def test_create_custom_dimension_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomDimension() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + custom_dimension=resources.CustomDimension(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 = resources.CustomDimension.pb(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_custom_dimension(**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/v1alpha/{parent=properties/*}/customDimensions" % client.transport._host, args[1]) + + +def test_create_custom_dimension_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_dimension( + analytics_admin.CreateCustomDimensionRequest(), + parent='parent_value', + custom_dimension=resources.CustomDimension(name='name_value'), + ) + + +def test_create_custom_dimension_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateCustomDimensionRequest, + dict, +]) +def test_update_custom_dimension_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'custom_dimension': {'name': 'properties/sample1/customDimensions/sample2'}} + request_init["custom_dimension"] = {'name': 'properties/sample1/customDimensions/sample2', 'parameter_name': 'parameter_name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'scope': 1, 'disallow_ads_personalization': 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 = analytics_admin.UpdateCustomDimensionRequest.meta.fields["custom_dimension"] + + 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["custom_dimension"].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["custom_dimension"][field])): + del request_init["custom_dimension"][field][i][subfield] + else: + del request_init["custom_dimension"][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 = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + +def test_update_custom_dimension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_custom_dimension] = mock_rpc + + request = {} + client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_custom_dimension_rest_required_fields(request_type=analytics_admin.UpdateCustomDimensionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_dimension._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_custom_dimension._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomDimension() + # 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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_custom_dimension_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_custom_dimension_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_custom_dimension") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_custom_dimension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateCustomDimensionRequest.pb(analytics_admin.UpdateCustomDimensionRequest()) + 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 = resources.CustomDimension.to_json(resources.CustomDimension()) + + request = analytics_admin.UpdateCustomDimensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomDimension() + + client.update_custom_dimension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_custom_dimension_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateCustomDimensionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'custom_dimension': {'name': 'properties/sample1/customDimensions/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_custom_dimension(request) + + +def test_update_custom_dimension_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomDimension() + + # get arguments that satisfy an http rule for this method + sample_request = {'custom_dimension': {'name': 'properties/sample1/customDimensions/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + custom_dimension=resources.CustomDimension(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 = resources.CustomDimension.pb(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_custom_dimension(**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/v1alpha/{custom_dimension.name=properties/*/customDimensions/*}" % client.transport._host, args[1]) + + +def test_update_custom_dimension_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_dimension( + analytics_admin.UpdateCustomDimensionRequest(), + custom_dimension=resources.CustomDimension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_custom_dimension_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCustomDimensionsRequest, + dict, +]) +def test_list_custom_dimensions_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListCustomDimensionsResponse( + 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 = analytics_admin.ListCustomDimensionsResponse.pb(return_value) + 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_custom_dimensions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomDimensionsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_custom_dimensions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_custom_dimensions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_custom_dimensions] = mock_rpc + + request = {} + client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_custom_dimensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_custom_dimensions_rest_required_fields(request_type=analytics_admin.ListCustomDimensionsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_dimensions._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_custom_dimensions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListCustomDimensionsResponse() + # 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 = analytics_admin.ListCustomDimensionsResponse.pb(return_value) + 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_custom_dimensions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_custom_dimensions_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_custom_dimensions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_custom_dimensions_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_custom_dimensions") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_custom_dimensions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListCustomDimensionsRequest.pb(analytics_admin.ListCustomDimensionsRequest()) + 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 = analytics_admin.ListCustomDimensionsResponse.to_json(analytics_admin.ListCustomDimensionsResponse()) + + request = analytics_admin.ListCustomDimensionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListCustomDimensionsResponse() + + client.list_custom_dimensions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_custom_dimensions_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListCustomDimensionsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_custom_dimensions(request) + + +def test_list_custom_dimensions_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCustomDimensionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListCustomDimensionsResponse.pb(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_custom_dimensions(**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/v1alpha/{parent=properties/*}/customDimensions" % client.transport._host, args[1]) + + +def test_list_custom_dimensions_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_dimensions( + analytics_admin.ListCustomDimensionsRequest(), + parent='parent_value', + ) + + +def test_list_custom_dimensions_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListCustomDimensionsResponse.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': 'properties/sample1'} + + pager = client.list_custom_dimensions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomDimension) + for i in results) + + pages = list(client.list_custom_dimensions(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", [ + analytics_admin.ArchiveCustomDimensionRequest, + dict, +]) +def test_archive_custom_dimension_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customDimensions/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.archive_custom_dimension(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_archive_custom_dimension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_custom_dimension] = mock_rpc + + request = {} + client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_archive_custom_dimension_rest_required_fields(request_type=analytics_admin.ArchiveCustomDimensionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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()).archive_custom_dimension._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()).archive_custom_dimension._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 = AnalyticsAdminServiceClient( + 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': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.archive_custom_dimension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_archive_custom_dimension_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.archive_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_archive_custom_dimension_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_archive_custom_dimension") as pre: + pre.assert_not_called() + pb_message = analytics_admin.ArchiveCustomDimensionRequest.pb(analytics_admin.ArchiveCustomDimensionRequest()) + 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 = analytics_admin.ArchiveCustomDimensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.archive_custom_dimension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_archive_custom_dimension_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ArchiveCustomDimensionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customDimensions/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.archive_custom_dimension(request) + + +def test_archive_custom_dimension_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/customDimensions/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.archive_custom_dimension(**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/v1alpha/{name=properties/*/customDimensions/*}:archive" % client.transport._host, args[1]) + + +def test_archive_custom_dimension_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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.archive_custom_dimension( + analytics_admin.ArchiveCustomDimensionRequest(), + name='name_value', + ) + + +def test_archive_custom_dimension_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCustomDimensionRequest, + dict, +]) +def test_get_custom_dimension_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customDimensions/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 = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + +def test_get_custom_dimension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_custom_dimension] = mock_rpc + + request = {} + client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_custom_dimension_rest_required_fields(request_type=analytics_admin.GetCustomDimensionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_dimension._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_custom_dimension._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomDimension() + # 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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_custom_dimension_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_custom_dimension_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_custom_dimension") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_custom_dimension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetCustomDimensionRequest.pb(analytics_admin.GetCustomDimensionRequest()) + 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 = resources.CustomDimension.to_json(resources.CustomDimension()) + + request = analytics_admin.GetCustomDimensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomDimension() + + client.get_custom_dimension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_custom_dimension_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetCustomDimensionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customDimensions/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_custom_dimension(request) + + +def test_get_custom_dimension_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomDimension() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/customDimensions/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 = resources.CustomDimension.pb(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_custom_dimension(**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/v1alpha/{name=properties/*/customDimensions/*}" % client.transport._host, args[1]) + + +def test_get_custom_dimension_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_dimension( + analytics_admin.GetCustomDimensionRequest(), + name='name_value', + ) + + +def test_get_custom_dimension_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateCustomMetricRequest, + dict, +]) +def test_create_custom_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["custom_metric"] = {'name': 'name_value', 'parameter_name': 'parameter_name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'measurement_unit': 1, 'scope': 1, 'restricted_metric_type': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateCustomMetricRequest.meta.fields["custom_metric"] + + 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["custom_metric"].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["custom_metric"][field])): + del request_init["custom_metric"][field][i][subfield] + else: + del request_init["custom_metric"][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 = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + +def test_create_custom_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_custom_metric] = mock_rpc + + request = {} + client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_custom_metric_rest_required_fields(request_type=analytics_admin.CreateCustomMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_metric._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_custom_metric._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomMetric() + # 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 = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_custom_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "customMetric", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_custom_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_custom_metric") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_custom_metric") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateCustomMetricRequest.pb(analytics_admin.CreateCustomMetricRequest()) + 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 = resources.CustomMetric.to_json(resources.CustomMetric()) + + request = analytics_admin.CreateCustomMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomMetric() + + client.create_custom_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_custom_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateCustomMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_custom_metric(request) + + +def test_create_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + custom_metric=resources.CustomMetric(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 = resources.CustomMetric.pb(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_custom_metric(**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/v1alpha/{parent=properties/*}/customMetrics" % client.transport._host, args[1]) + + +def test_create_custom_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_metric( + analytics_admin.CreateCustomMetricRequest(), + parent='parent_value', + custom_metric=resources.CustomMetric(name='name_value'), + ) + + +def test_create_custom_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateCustomMetricRequest, + dict, +]) +def test_update_custom_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'custom_metric': {'name': 'properties/sample1/customMetrics/sample2'}} + request_init["custom_metric"] = {'name': 'properties/sample1/customMetrics/sample2', 'parameter_name': 'parameter_name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'measurement_unit': 1, 'scope': 1, 'restricted_metric_type': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateCustomMetricRequest.meta.fields["custom_metric"] + + 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["custom_metric"].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["custom_metric"][field])): + del request_init["custom_metric"][field][i][subfield] + else: + del request_init["custom_metric"][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 = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + +def test_update_custom_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_custom_metric] = mock_rpc + + request = {} + client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_custom_metric_rest_required_fields(request_type=analytics_admin.UpdateCustomMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_metric._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_custom_metric._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomMetric() + # 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 = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_custom_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_custom_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_custom_metric") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_custom_metric") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateCustomMetricRequest.pb(analytics_admin.UpdateCustomMetricRequest()) + 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 = resources.CustomMetric.to_json(resources.CustomMetric()) + + request = analytics_admin.UpdateCustomMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomMetric() + + client.update_custom_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_custom_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateCustomMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'custom_metric': {'name': 'properties/sample1/customMetrics/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_custom_metric(request) + + +def test_update_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {'custom_metric': {'name': 'properties/sample1/customMetrics/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + custom_metric=resources.CustomMetric(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 = resources.CustomMetric.pb(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_custom_metric(**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/v1alpha/{custom_metric.name=properties/*/customMetrics/*}" % client.transport._host, args[1]) + + +def test_update_custom_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_metric( + analytics_admin.UpdateCustomMetricRequest(), + custom_metric=resources.CustomMetric(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_custom_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCustomMetricsRequest, + dict, +]) +def test_list_custom_metrics_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListCustomMetricsResponse( + 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 = analytics_admin.ListCustomMetricsResponse.pb(return_value) + 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_custom_metrics(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomMetricsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_custom_metrics_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_custom_metrics in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_custom_metrics] = mock_rpc + + request = {} + client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_custom_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_custom_metrics_rest_required_fields(request_type=analytics_admin.ListCustomMetricsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_metrics._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_custom_metrics._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListCustomMetricsResponse() + # 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 = analytics_admin.ListCustomMetricsResponse.pb(return_value) + 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_custom_metrics(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_custom_metrics_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_custom_metrics._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_custom_metrics_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_custom_metrics") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_custom_metrics") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListCustomMetricsRequest.pb(analytics_admin.ListCustomMetricsRequest()) + 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 = analytics_admin.ListCustomMetricsResponse.to_json(analytics_admin.ListCustomMetricsResponse()) + + request = analytics_admin.ListCustomMetricsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListCustomMetricsResponse() + + client.list_custom_metrics(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_custom_metrics_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListCustomMetricsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_custom_metrics(request) + + +def test_list_custom_metrics_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCustomMetricsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListCustomMetricsResponse.pb(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_custom_metrics(**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/v1alpha/{parent=properties/*}/customMetrics" % client.transport._host, args[1]) + + +def test_list_custom_metrics_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_metrics( + analytics_admin.ListCustomMetricsRequest(), + parent='parent_value', + ) + + +def test_list_custom_metrics_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListCustomMetricsResponse.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': 'properties/sample1'} + + pager = client.list_custom_metrics(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomMetric) + for i in results) + + pages = list(client.list_custom_metrics(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", [ + analytics_admin.ArchiveCustomMetricRequest, + dict, +]) +def test_archive_custom_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customMetrics/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.archive_custom_metric(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_archive_custom_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_custom_metric] = mock_rpc + + request = {} + client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_archive_custom_metric_rest_required_fields(request_type=analytics_admin.ArchiveCustomMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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()).archive_custom_metric._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()).archive_custom_metric._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 = AnalyticsAdminServiceClient( + 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': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.archive_custom_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_archive_custom_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.archive_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_archive_custom_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_archive_custom_metric") as pre: + pre.assert_not_called() + pb_message = analytics_admin.ArchiveCustomMetricRequest.pb(analytics_admin.ArchiveCustomMetricRequest()) + 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 = analytics_admin.ArchiveCustomMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.archive_custom_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_archive_custom_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ArchiveCustomMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customMetrics/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.archive_custom_metric(request) + + +def test_archive_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/customMetrics/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.archive_custom_metric(**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/v1alpha/{name=properties/*/customMetrics/*}:archive" % client.transport._host, args[1]) + + +def test_archive_custom_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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.archive_custom_metric( + analytics_admin.ArchiveCustomMetricRequest(), + name='name_value', + ) + + +def test_archive_custom_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCustomMetricRequest, + dict, +]) +def test_get_custom_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customMetrics/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 = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + +def test_get_custom_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_custom_metric] = mock_rpc + + request = {} + client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_custom_metric_rest_required_fields(request_type=analytics_admin.GetCustomMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_metric._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_custom_metric._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomMetric() + # 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 = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_custom_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_custom_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_custom_metric") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_custom_metric") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetCustomMetricRequest.pb(analytics_admin.GetCustomMetricRequest()) + 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 = resources.CustomMetric.to_json(resources.CustomMetric()) + + request = analytics_admin.GetCustomMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomMetric() + + client.get_custom_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_custom_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetCustomMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customMetrics/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_custom_metric(request) + + +def test_get_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/customMetrics/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 = resources.CustomMetric.pb(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_custom_metric(**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/v1alpha/{name=properties/*/customMetrics/*}" % client.transport._host, args[1]) + + +def test_get_custom_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_metric( + analytics_admin.GetCustomMetricRequest(), + name='name_value', + ) + + +def test_get_custom_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataRetentionSettingsRequest, + dict, +]) +def test_get_data_retention_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataRetentionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_retention_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + +def test_get_data_retention_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_retention_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_retention_settings] = mock_rpc + + request = {} + client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_retention_settings_rest_required_fields(request_type=analytics_admin.GetDataRetentionSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_retention_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_retention_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataRetentionSettings() + # 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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_retention_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_retention_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_retention_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_retention_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_data_retention_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_retention_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetDataRetentionSettingsRequest.pb(analytics_admin.GetDataRetentionSettingsRequest()) + 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 = resources.DataRetentionSettings.to_json(resources.DataRetentionSettings()) + + request = analytics_admin.GetDataRetentionSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataRetentionSettings() + + client.get_data_retention_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_retention_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetDataRetentionSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataRetentionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_data_retention_settings(request) + + +def test_get_data_retention_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataRetentionSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataRetentionSettings'} + + # 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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_retention_settings(**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/v1alpha/{name=properties/*/dataRetentionSettings}" % client.transport._host, args[1]) + + +def test_get_data_retention_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_retention_settings( + analytics_admin.GetDataRetentionSettingsRequest(), + name='name_value', + ) + + +def test_get_data_retention_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDataRetentionSettingsRequest, + dict, +]) +def test_update_data_retention_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_retention_settings': {'name': 'properties/sample1/dataRetentionSettings'}} + request_init["data_retention_settings"] = {'name': 'properties/sample1/dataRetentionSettings', 'event_data_retention': 1, 'reset_user_data_on_new_activity': 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 = analytics_admin.UpdateDataRetentionSettingsRequest.meta.fields["data_retention_settings"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_retention_settings"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_retention_settings"][field])): + del request_init["data_retention_settings"][field][i][subfield] + else: + del request_init["data_retention_settings"][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 = resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_data_retention_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + +def test_update_data_retention_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_retention_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_retention_settings] = mock_rpc + + request = {} + client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_data_retention_settings_rest_required_fields(request_type=analytics_admin.UpdateDataRetentionSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_retention_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_retention_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataRetentionSettings() + # 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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_data_retention_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_data_retention_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_data_retention_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("dataRetentionSettings", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_retention_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_data_retention_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_data_retention_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateDataRetentionSettingsRequest.pb(analytics_admin.UpdateDataRetentionSettingsRequest()) + 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 = resources.DataRetentionSettings.to_json(resources.DataRetentionSettings()) + + request = analytics_admin.UpdateDataRetentionSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataRetentionSettings() + + client.update_data_retention_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_data_retention_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateDataRetentionSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_retention_settings': {'name': 'properties/sample1/dataRetentionSettings'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_data_retention_settings(request) + + +def test_update_data_retention_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataRetentionSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'data_retention_settings': {'name': 'properties/sample1/dataRetentionSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + data_retention_settings=resources.DataRetentionSettings(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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_data_retention_settings(**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/v1alpha/{data_retention_settings.name=properties/*/dataRetentionSettings}" % client.transport._host, args[1]) + + +def test_update_data_retention_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_retention_settings( + analytics_admin.UpdateDataRetentionSettingsRequest(), + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_data_retention_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateDataStreamRequest, + dict, +]) +def test_create_data_stream_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["data_stream"] = {'web_stream_data': {'measurement_id': 'measurement_id_value', 'firebase_app_id': 'firebase_app_id_value', 'default_uri': 'default_uri_value'}, 'android_app_stream_data': {'firebase_app_id': 'firebase_app_id_value', 'package_name': 'package_name_value'}, 'ios_app_stream_data': {'firebase_app_id': 'firebase_app_id_value', 'bundle_id': 'bundle_id_value'}, 'name': 'name_value', 'type_': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateDataStreamRequest.meta.fields["data_stream"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_stream"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_stream"][field])): + del request_init["data_stream"][field][i][subfield] + else: + del request_init["data_stream"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_data_stream(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + +def test_create_data_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_data_stream] = mock_rpc + + request = {} + client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_data_stream_rest_required_fields(request_type=analytics_admin.CreateDataStreamRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_stream._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataStream() + # 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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_data_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_data_stream_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "dataStream", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_data_stream_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_data_stream") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_data_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateDataStreamRequest.pb(analytics_admin.CreateDataStreamRequest()) + 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 = resources.DataStream.to_json(resources.DataStream()) + + request = analytics_admin.CreateDataStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataStream() + + client.create_data_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_data_stream_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateDataStreamRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_data_stream(request) + + +def test_create_data_stream_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataStream() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_data_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=properties/*}/dataStreams" % client.transport._host, args[1]) + + +def test_create_data_stream_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_data_stream( + analytics_admin.CreateDataStreamRequest(), + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + ) + + +def test_create_data_stream_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteDataStreamRequest, + dict, +]) +def test_delete_data_stream_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/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_data_stream(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_data_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_data_stream] = mock_rpc + + request = {} + client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_data_stream_rest_required_fields(request_type=analytics_admin.DeleteDataStreamRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_data_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_data_stream_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_data_stream_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_data_stream") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteDataStreamRequest.pb(analytics_admin.DeleteDataStreamRequest()) + 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 = analytics_admin.DeleteDataStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_data_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_data_stream_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteDataStreamRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/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_data_stream(request) + + +def test_delete_data_stream_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/dataStreams/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_data_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=properties/*/dataStreams/*}" % client.transport._host, args[1]) + + +def test_delete_data_stream_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_data_stream( + analytics_admin.DeleteDataStreamRequest(), + name='name_value', + ) + + +def test_delete_data_stream_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDataStreamRequest, + dict, +]) +def test_update_data_stream_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_stream': {'name': 'properties/sample1/dataStreams/sample2'}} + request_init["data_stream"] = {'web_stream_data': {'measurement_id': 'measurement_id_value', 'firebase_app_id': 'firebase_app_id_value', 'default_uri': 'default_uri_value'}, 'android_app_stream_data': {'firebase_app_id': 'firebase_app_id_value', 'package_name': 'package_name_value'}, 'ios_app_stream_data': {'firebase_app_id': 'firebase_app_id_value', 'bundle_id': 'bundle_id_value'}, 'name': 'properties/sample1/dataStreams/sample2', 'type_': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateDataStreamRequest.meta.fields["data_stream"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_stream"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_stream"][field])): + del request_init["data_stream"][field][i][subfield] + else: + del request_init["data_stream"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_data_stream(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + +def test_update_data_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_stream] = mock_rpc + + request = {} + client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_data_stream_rest_required_fields(request_type=analytics_admin.UpdateDataStreamRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_stream._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataStream() + # 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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_data_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_data_stream_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_stream_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_data_stream") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_data_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateDataStreamRequest.pb(analytics_admin.UpdateDataStreamRequest()) + 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 = resources.DataStream.to_json(resources.DataStream()) + + request = analytics_admin.UpdateDataStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataStream() + + client.update_data_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_data_stream_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateDataStreamRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_stream': {'name': 'properties/sample1/dataStreams/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_data_stream(request) + + +def test_update_data_stream_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataStream() + + # get arguments that satisfy an http rule for this method + sample_request = {'data_stream': {'name': 'properties/sample1/dataStreams/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_data_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{data_stream.name=properties/*/dataStreams/*}" % client.transport._host, args[1]) + + +def test_update_data_stream_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_stream( + analytics_admin.UpdateDataStreamRequest(), + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_data_stream_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListDataStreamsRequest, + dict, +]) +def test_list_data_streams_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListDataStreamsResponse( + 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 = analytics_admin.ListDataStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_data_streams(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataStreamsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_data_streams_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_streams in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_data_streams] = mock_rpc + + request = {} + client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_data_streams_rest_required_fields(request_type=analytics_admin.ListDataStreamsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_streams._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_streams._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListDataStreamsResponse() + # 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 = analytics_admin.ListDataStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_data_streams(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_data_streams_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_data_streams._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_data_streams_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_data_streams") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_data_streams") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListDataStreamsRequest.pb(analytics_admin.ListDataStreamsRequest()) + 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 = analytics_admin.ListDataStreamsResponse.to_json(analytics_admin.ListDataStreamsResponse()) + + request = analytics_admin.ListDataStreamsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListDataStreamsResponse() + + client.list_data_streams(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_data_streams_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListDataStreamsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_data_streams(request) + + +def test_list_data_streams_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListDataStreamsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListDataStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_data_streams(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{parent=properties/*}/dataStreams" % client.transport._host, args[1]) + + +def test_list_data_streams_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_streams( + analytics_admin.ListDataStreamsRequest(), + parent='parent_value', + ) + + +def test_list_data_streams_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListDataStreamsResponse.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': 'properties/sample1'} + + pager = client.list_data_streams(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DataStream) + for i in results) + + pages = list(client.list_data_streams(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataStreamRequest, + dict, +]) +def test_get_data_stream_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/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 = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_stream(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + +def test_get_data_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_stream] = mock_rpc + + request = {} + client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_stream_rest_required_fields(request_type=analytics_admin.GetDataStreamRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataStream() + # 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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_stream_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_stream_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_data_stream") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetDataStreamRequest.pb(analytics_admin.GetDataStreamRequest()) + 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 = resources.DataStream.to_json(resources.DataStream()) + + request = analytics_admin.GetDataStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataStream() + + client.get_data_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_stream_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetDataStreamRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/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_data_stream(request) + + +def test_get_data_stream_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataStream() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1alpha/{name=properties/*/dataStreams/*}" % client.transport._host, args[1]) + + +def test_get_data_stream_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_stream( + analytics_admin.GetDataStreamRequest(), + name='name_value', + ) + + +def test_get_data_stream_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAudienceRequest, + dict, +]) +def test_get_audience_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/audiences/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 = audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = audience.Audience.pb(return_value) + 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_audience(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, audience.Audience) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert response.exclusion_duration_mode == audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + +def test_get_audience_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_audience in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_audience] = mock_rpc + + request = {} + client.get_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_audience_rest_required_fields(request_type=analytics_admin.GetAudienceRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_audience._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_audience._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = audience.Audience() + # 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 = audience.Audience.pb(return_value) + 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_audience(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_audience_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_audience._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_audience_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_audience") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_audience") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetAudienceRequest.pb(analytics_admin.GetAudienceRequest()) + 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 = audience.Audience.to_json(audience.Audience()) + + request = analytics_admin.GetAudienceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = audience.Audience() + + client.get_audience(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_audience_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetAudienceRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/audiences/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_audience(request) + + +def test_get_audience_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = audience.Audience() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/audiences/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 = audience.Audience.pb(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_audience(**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/v1alpha/{name=properties/*/audiences/*}" % client.transport._host, args[1]) + + +def test_get_audience_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_audience( + analytics_admin.GetAudienceRequest(), + name='name_value', + ) + + +def test_get_audience_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAudiencesRequest, + dict, +]) +def test_list_audiences_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListAudiencesResponse( + 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 = analytics_admin.ListAudiencesResponse.pb(return_value) + 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_audiences(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAudiencesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_audiences_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_audiences in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_audiences] = mock_rpc + + request = {} + client.list_audiences(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_audiences(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_audiences_rest_required_fields(request_type=analytics_admin.ListAudiencesRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_audiences._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_audiences._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListAudiencesResponse() + # 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 = analytics_admin.ListAudiencesResponse.pb(return_value) + 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_audiences(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_audiences_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_audiences._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_audiences_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_audiences") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_audiences") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListAudiencesRequest.pb(analytics_admin.ListAudiencesRequest()) + 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 = analytics_admin.ListAudiencesResponse.to_json(analytics_admin.ListAudiencesResponse()) + + request = analytics_admin.ListAudiencesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListAudiencesResponse() + + client.list_audiences(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_audiences_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListAudiencesRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_audiences(request) + + +def test_list_audiences_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAudiencesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListAudiencesResponse.pb(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_audiences(**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/v1alpha/{parent=properties/*}/audiences" % client.transport._host, args[1]) + + +def test_list_audiences_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_audiences( + analytics_admin.ListAudiencesRequest(), + parent='parent_value', + ) + + +def test_list_audiences_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + audience.Audience(), + ], + next_page_token='abc', + ), + analytics_admin.ListAudiencesResponse( + audiences=[], + next_page_token='def', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAudiencesResponse( + audiences=[ + audience.Audience(), + audience.Audience(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListAudiencesResponse.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': 'properties/sample1'} + + pager = client.list_audiences(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, audience.Audience) + for i in results) + + pages = list(client.list_audiences(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", [ + analytics_admin.CreateAudienceRequest, + dict, +]) +def test_create_audience_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["audience"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'membership_duration_days': 2561, 'ads_personalization_enabled': True, 'event_trigger': {'event_name': 'event_name_value', 'log_condition': 1}, 'exclusion_duration_mode': 1, 'filter_clauses': [{'simple_filter': {'scope': 1, 'filter_expression': {'and_group': {'filter_expressions': {}}, 'or_group': {}, 'not_expression': {}, 'dimension_or_metric_filter': {'string_filter': {'match_type': 1, 'value': 'value_value', 'case_sensitive': True}, 'in_list_filter': {'values': ['values_value1', 'values_value2'], 'case_sensitive': True}, 'numeric_filter': {'operation': 1, 'value': {'int64_value': 1073, 'double_value': 0.12710000000000002}}, 'between_filter': {'from_value': {}, 'to_value': {}}, 'field_name': 'field_name_value', 'at_any_point_in_time': True, 'in_any_n_day_period': 1994}, 'event_filter': {'event_name': 'event_name_value', 'event_parameter_filter_expression': {}}}}, 'sequence_filter': {'scope': 1, 'sequence_maximum_duration': {'seconds': 751, 'nanos': 543}, 'sequence_steps': [{'scope': 1, 'immediately_follows': True, 'constraint_duration': {}, 'filter_expression': {}}]}, 'clause_type': 1}], 'create_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 = analytics_admin.CreateAudienceRequest.meta.fields["audience"] + + 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["audience"].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["audience"][field])): + del request_init["audience"][field][i][subfield] + else: + del request_init["audience"][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 = gaa_audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gaa_audience.Audience.pb(return_value) + 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_audience(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_audience.Audience) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert response.exclusion_duration_mode == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + +def test_create_audience_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_audience in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_audience] = mock_rpc + + request = {} + client.create_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_audience_rest_required_fields(request_type=analytics_admin.CreateAudienceRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_audience._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_audience._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gaa_audience.Audience() + # 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 = gaa_audience.Audience.pb(return_value) + 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_audience(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_audience_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_audience._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "audience", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_audience_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_audience") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_audience") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateAudienceRequest.pb(analytics_admin.CreateAudienceRequest()) + 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 = gaa_audience.Audience.to_json(gaa_audience.Audience()) + + request = analytics_admin.CreateAudienceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gaa_audience.Audience() + + client.create_audience(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_audience_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateAudienceRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_audience(request) + + +def test_create_audience_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = gaa_audience.Audience() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + audience=gaa_audience.Audience(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 = gaa_audience.Audience.pb(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_audience(**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/v1alpha/{parent=properties/*}/audiences" % client.transport._host, args[1]) + + +def test_create_audience_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_audience( + analytics_admin.CreateAudienceRequest(), + parent='parent_value', + audience=gaa_audience.Audience(name='name_value'), + ) + + +def test_create_audience_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAudienceRequest, + dict, +]) +def test_update_audience_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'audience': {'name': 'properties/sample1/audiences/sample2'}} + request_init["audience"] = {'name': 'properties/sample1/audiences/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'membership_duration_days': 2561, 'ads_personalization_enabled': True, 'event_trigger': {'event_name': 'event_name_value', 'log_condition': 1}, 'exclusion_duration_mode': 1, 'filter_clauses': [{'simple_filter': {'scope': 1, 'filter_expression': {'and_group': {'filter_expressions': {}}, 'or_group': {}, 'not_expression': {}, 'dimension_or_metric_filter': {'string_filter': {'match_type': 1, 'value': 'value_value', 'case_sensitive': True}, 'in_list_filter': {'values': ['values_value1', 'values_value2'], 'case_sensitive': True}, 'numeric_filter': {'operation': 1, 'value': {'int64_value': 1073, 'double_value': 0.12710000000000002}}, 'between_filter': {'from_value': {}, 'to_value': {}}, 'field_name': 'field_name_value', 'at_any_point_in_time': True, 'in_any_n_day_period': 1994}, 'event_filter': {'event_name': 'event_name_value', 'event_parameter_filter_expression': {}}}}, 'sequence_filter': {'scope': 1, 'sequence_maximum_duration': {'seconds': 751, 'nanos': 543}, 'sequence_steps': [{'scope': 1, 'immediately_follows': True, 'constraint_duration': {}, 'filter_expression': {}}]}, 'clause_type': 1}], 'create_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 = analytics_admin.UpdateAudienceRequest.meta.fields["audience"] + + 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["audience"].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["audience"][field])): + del request_init["audience"][field][i][subfield] + else: + del request_init["audience"][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 = gaa_audience.Audience( + name='name_value', + display_name='display_name_value', + description='description_value', + membership_duration_days=2561, + ads_personalization_enabled=True, + exclusion_duration_mode=gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gaa_audience.Audience.pb(return_value) + 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_audience(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_audience.Audience) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.membership_duration_days == 2561 + assert response.ads_personalization_enabled is True + assert response.exclusion_duration_mode == gaa_audience.Audience.AudienceExclusionDurationMode.EXCLUDE_TEMPORARILY + +def test_update_audience_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_audience in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_audience] = mock_rpc + + request = {} + client.update_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_audience_rest_required_fields(request_type=analytics_admin.UpdateAudienceRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_audience._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_audience._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gaa_audience.Audience() + # 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 = gaa_audience.Audience.pb(return_value) + 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_audience(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_audience_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_audience._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("audience", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_audience_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_audience") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_audience") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateAudienceRequest.pb(analytics_admin.UpdateAudienceRequest()) + 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 = gaa_audience.Audience.to_json(gaa_audience.Audience()) + + request = analytics_admin.UpdateAudienceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gaa_audience.Audience() + + client.update_audience(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_audience_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateAudienceRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'audience': {'name': 'properties/sample1/audiences/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_audience(request) + + +def test_update_audience_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = gaa_audience.Audience() + + # get arguments that satisfy an http rule for this method + sample_request = {'audience': {'name': 'properties/sample1/audiences/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + audience=gaa_audience.Audience(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 = gaa_audience.Audience.pb(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_audience(**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/v1alpha/{audience.name=properties/*/audiences/*}" % client.transport._host, args[1]) + + +def test_update_audience_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_audience( + analytics_admin.UpdateAudienceRequest(), + audience=gaa_audience.Audience(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_audience_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ArchiveAudienceRequest, + dict, +]) +def test_archive_audience_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/audiences/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.archive_audience(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_archive_audience_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_audience in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_audience] = mock_rpc + + request = {} + client.archive_audience(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_audience(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_archive_audience_rest_required_fields(request_type=analytics_admin.ArchiveAudienceRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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()).archive_audience._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()).archive_audience._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 = AnalyticsAdminServiceClient( + 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': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.archive_audience(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_archive_audience_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.archive_audience._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_archive_audience_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_archive_audience") as pre: + pre.assert_not_called() + pb_message = analytics_admin.ArchiveAudienceRequest.pb(analytics_admin.ArchiveAudienceRequest()) + 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 = analytics_admin.ArchiveAudienceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.archive_audience(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_archive_audience_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ArchiveAudienceRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/audiences/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.archive_audience(request) + + +def test_archive_audience_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetSearchAds360LinkRequest, + dict, +]) +def test_get_search_ads360_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/searchAds360Links/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 = resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_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 = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_search_ads360_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SearchAds360Link) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + +def test_get_search_ads360_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_search_ads360_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_search_ads360_link] = mock_rpc + + request = {} + client.get_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_search_ads360_link_rest_required_fields(request_type=analytics_admin.GetSearchAds360LinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_search_ads360_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_search_ads360_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.SearchAds360Link() + # 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 = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_search_ads360_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_search_ads360_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_search_ads360_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_search_ads360_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_search_ads360_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_search_ads360_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetSearchAds360LinkRequest.pb(analytics_admin.GetSearchAds360LinkRequest()) + 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 = resources.SearchAds360Link.to_json(resources.SearchAds360Link()) + + request = analytics_admin.GetSearchAds360LinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.SearchAds360Link() + + client.get_search_ads360_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_search_ads360_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetSearchAds360LinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/searchAds360Links/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_search_ads360_link(request) + + +def test_get_search_ads360_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.SearchAds360Link() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/searchAds360Links/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 = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_search_ads360_link(**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/v1alpha/{name=properties/*/searchAds360Links/*}" % client.transport._host, args[1]) + + +def test_get_search_ads360_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_search_ads360_link( + analytics_admin.GetSearchAds360LinkRequest(), + name='name_value', + ) + + +def test_get_search_ads360_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListSearchAds360LinksRequest, + dict, +]) +def test_list_search_ads360_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListSearchAds360LinksResponse( + 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 = analytics_admin.ListSearchAds360LinksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_search_ads360_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSearchAds360LinksPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_search_ads360_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_search_ads360_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_search_ads360_links] = mock_rpc + + request = {} + client.list_search_ads360_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_search_ads360_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_search_ads360_links_rest_required_fields(request_type=analytics_admin.ListSearchAds360LinksRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_search_ads360_links._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_search_ads360_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListSearchAds360LinksResponse() + # 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 = analytics_admin.ListSearchAds360LinksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_search_ads360_links(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_search_ads360_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_search_ads360_links._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_search_ads360_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_search_ads360_links") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_search_ads360_links") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListSearchAds360LinksRequest.pb(analytics_admin.ListSearchAds360LinksRequest()) + 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 = analytics_admin.ListSearchAds360LinksResponse.to_json(analytics_admin.ListSearchAds360LinksResponse()) + + request = analytics_admin.ListSearchAds360LinksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListSearchAds360LinksResponse() + + client.list_search_ads360_links(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_search_ads360_links_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListSearchAds360LinksRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_search_ads360_links(request) + + +def test_list_search_ads360_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListSearchAds360LinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListSearchAds360LinksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_search_ads360_links(**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/v1alpha/{parent=properties/*}/searchAds360Links" % client.transport._host, args[1]) + + +def test_list_search_ads360_links_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_search_ads360_links( + analytics_admin.ListSearchAds360LinksRequest(), + parent='parent_value', + ) + + +def test_list_search_ads360_links_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + next_page_token='abc', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[], + next_page_token='def', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSearchAds360LinksResponse( + search_ads_360_links=[ + resources.SearchAds360Link(), + resources.SearchAds360Link(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListSearchAds360LinksResponse.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': 'properties/sample1'} + + pager = client.list_search_ads360_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SearchAds360Link) + for i in results) + + pages = list(client.list_search_ads360_links(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", [ + analytics_admin.CreateSearchAds360LinkRequest, + dict, +]) +def test_create_search_ads360_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["search_ads_360_link"] = {'name': 'name_value', 'advertiser_id': 'advertiser_id_value', 'campaign_data_sharing_enabled': {'value': True}, 'cost_data_sharing_enabled': {}, 'advertiser_display_name': 'advertiser_display_name_value', 'ads_personalization_enabled': {}, 'site_stats_sharing_enabled': {}} + # 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 = analytics_admin.CreateSearchAds360LinkRequest.meta.fields["search_ads_360_link"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["search_ads_360_link"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["search_ads_360_link"][field])): + del request_init["search_ads_360_link"][field][i][subfield] + else: + del request_init["search_ads_360_link"][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 = resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_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 = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_search_ads360_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SearchAds360Link) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + +def test_create_search_ads360_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_search_ads360_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_search_ads360_link] = mock_rpc + + request = {} + client.create_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_search_ads360_link_rest_required_fields(request_type=analytics_admin.CreateSearchAds360LinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_search_ads360_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_search_ads360_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.SearchAds360Link() + # 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 = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_search_ads360_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_search_ads360_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_search_ads360_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "searchAds360Link", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_search_ads360_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_search_ads360_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_search_ads360_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateSearchAds360LinkRequest.pb(analytics_admin.CreateSearchAds360LinkRequest()) + 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 = resources.SearchAds360Link.to_json(resources.SearchAds360Link()) + + request = analytics_admin.CreateSearchAds360LinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.SearchAds360Link() + + client.create_search_ads360_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_search_ads360_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateSearchAds360LinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_search_ads360_link(request) + + +def test_create_search_ads360_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.SearchAds360Link() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + search_ads_360_link=resources.SearchAds360Link(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 = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_search_ads360_link(**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/v1alpha/{parent=properties/*}/searchAds360Links" % client.transport._host, args[1]) + + +def test_create_search_ads360_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_search_ads360_link( + analytics_admin.CreateSearchAds360LinkRequest(), + parent='parent_value', + search_ads_360_link=resources.SearchAds360Link(name='name_value'), + ) + + +def test_create_search_ads360_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteSearchAds360LinkRequest, + dict, +]) +def test_delete_search_ads360_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/searchAds360Links/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_search_ads360_link(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_search_ads360_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_search_ads360_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_search_ads360_link] = mock_rpc + + request = {} + client.delete_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_search_ads360_link_rest_required_fields(request_type=analytics_admin.DeleteSearchAds360LinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_search_ads360_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_search_ads360_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_search_ads360_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_search_ads360_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_search_ads360_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_search_ads360_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_search_ads360_link") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteSearchAds360LinkRequest.pb(analytics_admin.DeleteSearchAds360LinkRequest()) + 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 = analytics_admin.DeleteSearchAds360LinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_search_ads360_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_search_ads360_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteSearchAds360LinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/searchAds360Links/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_search_ads360_link(request) + + +def test_delete_search_ads360_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/searchAds360Links/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_search_ads360_link(**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/v1alpha/{name=properties/*/searchAds360Links/*}" % client.transport._host, args[1]) + + +def test_delete_search_ads360_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_search_ads360_link( + analytics_admin.DeleteSearchAds360LinkRequest(), + name='name_value', + ) + + +def test_delete_search_ads360_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateSearchAds360LinkRequest, + dict, +]) +def test_update_search_ads360_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'search_ads_360_link': {'name': 'properties/sample1/searchAds360Links/sample2'}} + request_init["search_ads_360_link"] = {'name': 'properties/sample1/searchAds360Links/sample2', 'advertiser_id': 'advertiser_id_value', 'campaign_data_sharing_enabled': {'value': True}, 'cost_data_sharing_enabled': {}, 'advertiser_display_name': 'advertiser_display_name_value', 'ads_personalization_enabled': {}, 'site_stats_sharing_enabled': {}} + # 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 = analytics_admin.UpdateSearchAds360LinkRequest.meta.fields["search_ads_360_link"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["search_ads_360_link"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["search_ads_360_link"][field])): + del request_init["search_ads_360_link"][field][i][subfield] + else: + del request_init["search_ads_360_link"][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 = resources.SearchAds360Link( + name='name_value', + advertiser_id='advertiser_id_value', + advertiser_display_name='advertiser_display_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 = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_search_ads360_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SearchAds360Link) + assert response.name == 'name_value' + assert response.advertiser_id == 'advertiser_id_value' + assert response.advertiser_display_name == 'advertiser_display_name_value' + +def test_update_search_ads360_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_search_ads360_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_search_ads360_link] = mock_rpc + + request = {} + client.update_search_ads360_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_search_ads360_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_search_ads360_link_rest_required_fields(request_type=analytics_admin.UpdateSearchAds360LinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_search_ads360_link._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_search_ads360_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.SearchAds360Link() + # 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 = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_search_ads360_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_search_ads360_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_search_ads360_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_search_ads360_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_search_ads360_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_search_ads360_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateSearchAds360LinkRequest.pb(analytics_admin.UpdateSearchAds360LinkRequest()) + 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 = resources.SearchAds360Link.to_json(resources.SearchAds360Link()) + + request = analytics_admin.UpdateSearchAds360LinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.SearchAds360Link() + + client.update_search_ads360_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_search_ads360_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateSearchAds360LinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'search_ads_360_link': {'name': 'properties/sample1/searchAds360Links/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_search_ads360_link(request) + + +def test_update_search_ads360_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.SearchAds360Link() + + # get arguments that satisfy an http rule for this method + sample_request = {'search_ads_360_link': {'name': 'properties/sample1/searchAds360Links/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + search_ads_360_link=resources.SearchAds360Link(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 = resources.SearchAds360Link.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_search_ads360_link(**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/v1alpha/{search_ads_360_link.name=properties/*/searchAds360Links/*}" % client.transport._host, args[1]) + + +def test_update_search_ads360_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_search_ads360_link( + analytics_admin.UpdateSearchAds360LinkRequest(), + search_ads_360_link=resources.SearchAds360Link(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_search_ads360_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAttributionSettingsRequest, + dict, +]) +def test_get_attribution_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/attributionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.AttributionSettings( + name='name_value', + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.AttributionSettings.pb(return_value) + 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_attribution_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AttributionSettings) + assert response.name == 'name_value' + assert response.acquisition_conversion_event_lookback_window == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + assert response.other_conversion_event_lookback_window == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + assert response.reporting_attribution_model == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + assert response.ads_web_conversion_data_export_scope == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + +def test_get_attribution_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_attribution_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_attribution_settings] = mock_rpc + + request = {} + client.get_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_attribution_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_attribution_settings_rest_required_fields(request_type=analytics_admin.GetAttributionSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_attribution_settings._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_attribution_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AttributionSettings() + # 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 = resources.AttributionSettings.pb(return_value) + 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_attribution_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_attribution_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_attribution_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_attribution_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_attribution_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_attribution_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetAttributionSettingsRequest.pb(analytics_admin.GetAttributionSettingsRequest()) + 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 = resources.AttributionSettings.to_json(resources.AttributionSettings()) + + request = analytics_admin.GetAttributionSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.AttributionSettings() + + client.get_attribution_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_attribution_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetAttributionSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/attributionSettings'} + 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_attribution_settings(request) + + +def test_get_attribution_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.AttributionSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/attributionSettings'} + + # 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 = resources.AttributionSettings.pb(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_attribution_settings(**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/v1alpha/{name=properties/*/attributionSettings}" % client.transport._host, args[1]) + + +def test_get_attribution_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_attribution_settings( + analytics_admin.GetAttributionSettingsRequest(), + name='name_value', + ) + + +def test_get_attribution_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAttributionSettingsRequest, + dict, +]) +def test_update_attribution_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'attribution_settings': {'name': 'properties/sample1/attributionSettings'}} + request_init["attribution_settings"] = {'name': 'properties/sample1/attributionSettings', 'acquisition_conversion_event_lookback_window': 1, 'other_conversion_event_lookback_window': 1, 'reporting_attribution_model': 1, 'ads_web_conversion_data_export_scope': 1} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateAttributionSettingsRequest.meta.fields["attribution_settings"] + + 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["attribution_settings"].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["attribution_settings"][field])): + del request_init["attribution_settings"][field][i][subfield] + else: + del request_init["attribution_settings"][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 = resources.AttributionSettings( + name='name_value', + acquisition_conversion_event_lookback_window=resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS, + other_conversion_event_lookback_window=resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS, + reporting_attribution_model=resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN, + ads_web_conversion_data_export_scope=resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.AttributionSettings.pb(return_value) + 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_attribution_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AttributionSettings) + assert response.name == 'name_value' + assert response.acquisition_conversion_event_lookback_window == resources.AttributionSettings.AcquisitionConversionEventLookbackWindow.ACQUISITION_CONVERSION_EVENT_LOOKBACK_WINDOW_7_DAYS + assert response.other_conversion_event_lookback_window == resources.AttributionSettings.OtherConversionEventLookbackWindow.OTHER_CONVERSION_EVENT_LOOKBACK_WINDOW_30_DAYS + assert response.reporting_attribution_model == resources.AttributionSettings.ReportingAttributionModel.PAID_AND_ORGANIC_CHANNELS_DATA_DRIVEN + assert response.ads_web_conversion_data_export_scope == resources.AttributionSettings.AdsWebConversionDataExportScope.NOT_SELECTED_YET + +def test_update_attribution_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_attribution_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_attribution_settings] = mock_rpc + + request = {} + client.update_attribution_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_attribution_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_attribution_settings_rest_required_fields(request_type=analytics_admin.UpdateAttributionSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_attribution_settings._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_attribution_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AttributionSettings() + # 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 = resources.AttributionSettings.pb(return_value) + 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_attribution_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_attribution_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_attribution_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("attributionSettings", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_attribution_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_attribution_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_attribution_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateAttributionSettingsRequest.pb(analytics_admin.UpdateAttributionSettingsRequest()) + 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 = resources.AttributionSettings.to_json(resources.AttributionSettings()) + + request = analytics_admin.UpdateAttributionSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.AttributionSettings() + + client.update_attribution_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_attribution_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateAttributionSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'attribution_settings': {'name': 'properties/sample1/attributionSettings'}} + 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_attribution_settings(request) + + +def test_update_attribution_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.AttributionSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'attribution_settings': {'name': 'properties/sample1/attributionSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + attribution_settings=resources.AttributionSettings(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 = resources.AttributionSettings.pb(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_attribution_settings(**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/v1alpha/{attribution_settings.name=properties/*/attributionSettings}" % client.transport._host, args[1]) + + +def test_update_attribution_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_attribution_settings( + analytics_admin.UpdateAttributionSettingsRequest(), + attribution_settings=resources.AttributionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_attribution_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.RunAccessReportRequest, + dict, +]) +def test_run_access_report_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'entity': 'properties/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 = analytics_admin.RunAccessReportResponse( + row_count=992, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.RunAccessReportResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.run_access_report(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.RunAccessReportResponse) + assert response.row_count == 992 + +def test_run_access_report_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_access_report in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_access_report] = mock_rpc + + request = {} + client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_access_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_access_report_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_run_access_report") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_run_access_report") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.RunAccessReportRequest.pb(analytics_admin.RunAccessReportRequest()) + 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 = analytics_admin.RunAccessReportResponse.to_json(analytics_admin.RunAccessReportResponse()) + + request = analytics_admin.RunAccessReportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.RunAccessReportResponse() + + client.run_access_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_access_report_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.RunAccessReportRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'entity': 'properties/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.run_access_report(request) + + +def test_run_access_report_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateAccessBindingRequest, + dict, +]) +def test_create_access_binding_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/sample1'} + request_init["access_binding"] = {'user': 'user_value', 'name': 'name_value', 'roles': ['roles_value1', 'roles_value2']} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateAccessBindingRequest.meta.fields["access_binding"] + + 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["access_binding"].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["access_binding"][field])): + del request_init["access_binding"][field][i][subfield] + else: + del request_init["access_binding"][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 = resources.AccessBinding( + name='name_value', + roles=['roles_value'], + user='user_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 = resources.AccessBinding.pb(return_value) + 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_access_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == 'name_value' + assert response.roles == ['roles_value'] + +def test_create_access_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_access_binding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_access_binding] = mock_rpc + + request = {} + client.create_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_access_binding_rest_required_fields(request_type=analytics_admin.CreateAccessBindingRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_access_binding._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_access_binding._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AccessBinding() + # 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 = resources.AccessBinding.pb(return_value) + 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_access_binding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_access_binding_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_access_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "accessBinding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_access_binding_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_access_binding") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_access_binding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateAccessBindingRequest.pb(analytics_admin.CreateAccessBindingRequest()) + 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 = resources.AccessBinding.to_json(resources.AccessBinding()) + + request = analytics_admin.CreateAccessBindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.AccessBinding() + + client.create_access_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_access_binding_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateAccessBindingRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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_access_binding(request) + + +def test_create_access_binding_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.AccessBinding() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + access_binding=resources.AccessBinding(user='user_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 = resources.AccessBinding.pb(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_access_binding(**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/v1alpha/{parent=accounts/*}/accessBindings" % client.transport._host, args[1]) + + +def test_create_access_binding_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_access_binding( + analytics_admin.CreateAccessBindingRequest(), + parent='parent_value', + access_binding=resources.AccessBinding(user='user_value'), + ) + + +def test_create_access_binding_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAccessBindingRequest, + dict, +]) +def test_get_access_binding_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/accessBindings/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 = resources.AccessBinding( + name='name_value', + roles=['roles_value'], + user='user_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 = resources.AccessBinding.pb(return_value) + 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_access_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == 'name_value' + assert response.roles == ['roles_value'] + +def test_get_access_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_access_binding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_access_binding] = mock_rpc + + request = {} + client.get_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_access_binding_rest_required_fields(request_type=analytics_admin.GetAccessBindingRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_access_binding._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_access_binding._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AccessBinding() + # 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 = resources.AccessBinding.pb(return_value) + 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_access_binding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_access_binding_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_access_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_access_binding_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_access_binding") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_access_binding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetAccessBindingRequest.pb(analytics_admin.GetAccessBindingRequest()) + 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 = resources.AccessBinding.to_json(resources.AccessBinding()) + + request = analytics_admin.GetAccessBindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.AccessBinding() + + client.get_access_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_access_binding_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetAccessBindingRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/accessBindings/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_access_binding(request) + + +def test_get_access_binding_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.AccessBinding() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/accessBindings/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 = resources.AccessBinding.pb(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_access_binding(**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/v1alpha/{name=accounts/*/accessBindings/*}" % client.transport._host, args[1]) + + +def test_get_access_binding_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_access_binding( + analytics_admin.GetAccessBindingRequest(), + name='name_value', + ) + + +def test_get_access_binding_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAccessBindingRequest, + dict, +]) +def test_update_access_binding_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'access_binding': {'name': 'accounts/sample1/accessBindings/sample2'}} + request_init["access_binding"] = {'user': 'user_value', 'name': 'accounts/sample1/accessBindings/sample2', 'roles': ['roles_value1', 'roles_value2']} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateAccessBindingRequest.meta.fields["access_binding"] + + 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["access_binding"].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["access_binding"][field])): + del request_init["access_binding"][field][i][subfield] + else: + del request_init["access_binding"][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 = resources.AccessBinding( + name='name_value', + roles=['roles_value'], + user='user_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 = resources.AccessBinding.pb(return_value) + 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_access_binding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AccessBinding) + assert response.name == 'name_value' + assert response.roles == ['roles_value'] + +def test_update_access_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_access_binding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_access_binding] = mock_rpc + + request = {} + client.update_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_access_binding_rest_required_fields(request_type=analytics_admin.UpdateAccessBindingRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_access_binding._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_access_binding._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AccessBinding() + # 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 = resources.AccessBinding.pb(return_value) + 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_access_binding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_access_binding_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_access_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("accessBinding", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_access_binding_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_access_binding") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_access_binding") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateAccessBindingRequest.pb(analytics_admin.UpdateAccessBindingRequest()) + 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 = resources.AccessBinding.to_json(resources.AccessBinding()) + + request = analytics_admin.UpdateAccessBindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.AccessBinding() + + client.update_access_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_access_binding_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateAccessBindingRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'access_binding': {'name': 'accounts/sample1/accessBindings/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_access_binding(request) + + +def test_update_access_binding_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.AccessBinding() + + # get arguments that satisfy an http rule for this method + sample_request = {'access_binding': {'name': 'accounts/sample1/accessBindings/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + access_binding=resources.AccessBinding(user='user_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 = resources.AccessBinding.pb(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_access_binding(**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/v1alpha/{access_binding.name=accounts/*/accessBindings/*}" % client.transport._host, args[1]) + + +def test_update_access_binding_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_access_binding( + analytics_admin.UpdateAccessBindingRequest(), + access_binding=resources.AccessBinding(user='user_value'), + ) + + +def test_update_access_binding_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteAccessBindingRequest, + dict, +]) +def test_delete_access_binding_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/accessBindings/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_access_binding(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_access_binding_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_access_binding in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_access_binding] = mock_rpc + + request = {} + client.delete_access_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_access_binding(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_access_binding_rest_required_fields(request_type=analytics_admin.DeleteAccessBindingRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_access_binding._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_access_binding._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 = AnalyticsAdminServiceClient( + 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_access_binding(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_access_binding_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_access_binding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_access_binding_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_access_binding") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteAccessBindingRequest.pb(analytics_admin.DeleteAccessBindingRequest()) + 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 = analytics_admin.DeleteAccessBindingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_access_binding(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_access_binding_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteAccessBindingRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/accessBindings/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_access_binding(request) + + +def test_delete_access_binding_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'accounts/sample1/accessBindings/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_access_binding(**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/v1alpha/{name=accounts/*/accessBindings/*}" % client.transport._host, args[1]) + + +def test_delete_access_binding_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_access_binding( + analytics_admin.DeleteAccessBindingRequest(), + name='name_value', + ) + + +def test_delete_access_binding_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccessBindingsRequest, + dict, +]) +def test_list_access_bindings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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 = analytics_admin.ListAccessBindingsResponse( + 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 = analytics_admin.ListAccessBindingsResponse.pb(return_value) + 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_access_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccessBindingsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_access_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_access_bindings] = mock_rpc + + request = {} + client.list_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_access_bindings_rest_required_fields(request_type=analytics_admin.ListAccessBindingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_access_bindings._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_access_bindings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListAccessBindingsResponse() + # 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 = analytics_admin.ListAccessBindingsResponse.pb(return_value) + 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_access_bindings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_access_bindings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_access_bindings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_access_bindings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_access_bindings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_access_bindings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListAccessBindingsRequest.pb(analytics_admin.ListAccessBindingsRequest()) + 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 = analytics_admin.ListAccessBindingsResponse.to_json(analytics_admin.ListAccessBindingsResponse()) + + request = analytics_admin.ListAccessBindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListAccessBindingsResponse() + + client.list_access_bindings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_access_bindings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListAccessBindingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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_access_bindings(request) + + +def test_list_access_bindings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccessBindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'accounts/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 = analytics_admin.ListAccessBindingsResponse.pb(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_access_bindings(**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/v1alpha/{parent=accounts/*}/accessBindings" % client.transport._host, args[1]) + + +def test_list_access_bindings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_access_bindings( + analytics_admin.ListAccessBindingsRequest(), + parent='parent_value', + ) + + +def test_list_access_bindings_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + resources.AccessBinding(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[], + next_page_token='def', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccessBindingsResponse( + access_bindings=[ + resources.AccessBinding(), + resources.AccessBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListAccessBindingsResponse.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': 'accounts/sample1'} + + pager = client.list_access_bindings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AccessBinding) + for i in results) + + pages = list(client.list_access_bindings(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", [ + analytics_admin.BatchCreateAccessBindingsRequest, + dict, +]) +def test_batch_create_access_bindings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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 = analytics_admin.BatchCreateAccessBindingsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.BatchCreateAccessBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_create_access_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.BatchCreateAccessBindingsResponse) + +def test_batch_create_access_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_create_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_create_access_bindings] = mock_rpc + + request = {} + client.batch_create_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_create_access_bindings_rest_required_fields(request_type=analytics_admin.BatchCreateAccessBindingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_access_bindings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_create_access_bindings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.BatchCreateAccessBindingsResponse() + # 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 = analytics_admin.BatchCreateAccessBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_create_access_bindings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_create_access_bindings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_create_access_bindings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_access_bindings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_batch_create_access_bindings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_batch_create_access_bindings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.BatchCreateAccessBindingsRequest.pb(analytics_admin.BatchCreateAccessBindingsRequest()) + 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 = analytics_admin.BatchCreateAccessBindingsResponse.to_json(analytics_admin.BatchCreateAccessBindingsResponse()) + + request = analytics_admin.BatchCreateAccessBindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.BatchCreateAccessBindingsResponse() + + client.batch_create_access_bindings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_create_access_bindings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.BatchCreateAccessBindingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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.batch_create_access_bindings(request) + + +def test_batch_create_access_bindings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.BatchGetAccessBindingsRequest, + dict, +]) +def test_batch_get_access_bindings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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 = analytics_admin.BatchGetAccessBindingsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.BatchGetAccessBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_get_access_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.BatchGetAccessBindingsResponse) + +def test_batch_get_access_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_get_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_get_access_bindings] = mock_rpc + + request = {} + client.batch_get_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_get_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_get_access_bindings_rest_required_fields(request_type=analytics_admin.BatchGetAccessBindingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["names"] = "" + 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 "names" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_get_access_bindings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "names" in jsonified_request + assert jsonified_request["names"] == request_init["names"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["names"] = 'names_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_get_access_bindings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("names", )) + 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 "names" in jsonified_request + assert jsonified_request["names"] == 'names_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.BatchGetAccessBindingsResponse() + # 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 = analytics_admin.BatchGetAccessBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_get_access_bindings(request) + + expected_params = [ + ( + "names", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_get_access_bindings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_get_access_bindings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("names", )) & set(("parent", "names", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_get_access_bindings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_batch_get_access_bindings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_batch_get_access_bindings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.BatchGetAccessBindingsRequest.pb(analytics_admin.BatchGetAccessBindingsRequest()) + 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 = analytics_admin.BatchGetAccessBindingsResponse.to_json(analytics_admin.BatchGetAccessBindingsResponse()) + + request = analytics_admin.BatchGetAccessBindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.BatchGetAccessBindingsResponse() + + client.batch_get_access_bindings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_get_access_bindings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.BatchGetAccessBindingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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.batch_get_access_bindings(request) + + +def test_batch_get_access_bindings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.BatchUpdateAccessBindingsRequest, + dict, +]) +def test_batch_update_access_bindings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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 = analytics_admin.BatchUpdateAccessBindingsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.BatchUpdateAccessBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_update_access_bindings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.BatchUpdateAccessBindingsResponse) + +def test_batch_update_access_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_update_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_update_access_bindings] = mock_rpc + + request = {} + client.batch_update_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_update_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_update_access_bindings_rest_required_fields(request_type=analytics_admin.BatchUpdateAccessBindingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_access_bindings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_update_access_bindings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.BatchUpdateAccessBindingsResponse() + # 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 = analytics_admin.BatchUpdateAccessBindingsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_update_access_bindings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_update_access_bindings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_update_access_bindings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_update_access_bindings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_batch_update_access_bindings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_batch_update_access_bindings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.BatchUpdateAccessBindingsRequest.pb(analytics_admin.BatchUpdateAccessBindingsRequest()) + 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 = analytics_admin.BatchUpdateAccessBindingsResponse.to_json(analytics_admin.BatchUpdateAccessBindingsResponse()) + + request = analytics_admin.BatchUpdateAccessBindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.BatchUpdateAccessBindingsResponse() + + client.batch_update_access_bindings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_update_access_bindings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.BatchUpdateAccessBindingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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.batch_update_access_bindings(request) + + +def test_batch_update_access_bindings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.BatchDeleteAccessBindingsRequest, + dict, +]) +def test_batch_delete_access_bindings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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.batch_delete_access_bindings(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_batch_delete_access_bindings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.batch_delete_access_bindings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.batch_delete_access_bindings] = mock_rpc + + request = {} + client.batch_delete_access_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_delete_access_bindings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_delete_access_bindings_rest_required_fields(request_type=analytics_admin.BatchDeleteAccessBindingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_access_bindings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_delete_access_bindings._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 = AnalyticsAdminServiceClient( + 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': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_delete_access_bindings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_delete_access_bindings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_delete_access_bindings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "requests", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_delete_access_bindings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_batch_delete_access_bindings") as pre: + pre.assert_not_called() + pb_message = analytics_admin.BatchDeleteAccessBindingsRequest.pb(analytics_admin.BatchDeleteAccessBindingsRequest()) + 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 = analytics_admin.BatchDeleteAccessBindingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.batch_delete_access_bindings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_batch_delete_access_bindings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.BatchDeleteAccessBindingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'accounts/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.batch_delete_access_bindings(request) + + +def test_batch_delete_access_bindings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetExpandedDataSetRequest, + dict, +]) +def test_get_expanded_data_set_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/expandedDataSets/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 = expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_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 = expanded_data_set.ExpandedDataSet.pb(return_value) + 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_expanded_data_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, expanded_data_set.ExpandedDataSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.dimension_names == ['dimension_names_value'] + assert response.metric_names == ['metric_names_value'] + +def test_get_expanded_data_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_expanded_data_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_expanded_data_set] = mock_rpc + + request = {} + client.get_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_expanded_data_set_rest_required_fields(request_type=analytics_admin.GetExpandedDataSetRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_expanded_data_set._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_expanded_data_set._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = expanded_data_set.ExpandedDataSet() + # 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 = expanded_data_set.ExpandedDataSet.pb(return_value) + 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_expanded_data_set(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_expanded_data_set_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_expanded_data_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_expanded_data_set_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_expanded_data_set") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_expanded_data_set") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetExpandedDataSetRequest.pb(analytics_admin.GetExpandedDataSetRequest()) + 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 = expanded_data_set.ExpandedDataSet.to_json(expanded_data_set.ExpandedDataSet()) + + request = analytics_admin.GetExpandedDataSetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = expanded_data_set.ExpandedDataSet() + + client.get_expanded_data_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_expanded_data_set_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetExpandedDataSetRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/expandedDataSets/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_expanded_data_set(request) + + +def test_get_expanded_data_set_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = expanded_data_set.ExpandedDataSet() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/expandedDataSets/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 = expanded_data_set.ExpandedDataSet.pb(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_expanded_data_set(**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/v1alpha/{name=properties/*/expandedDataSets/*}" % client.transport._host, args[1]) + + +def test_get_expanded_data_set_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_expanded_data_set( + analytics_admin.GetExpandedDataSetRequest(), + name='name_value', + ) + + +def test_get_expanded_data_set_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListExpandedDataSetsRequest, + dict, +]) +def test_list_expanded_data_sets_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListExpandedDataSetsResponse( + 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 = analytics_admin.ListExpandedDataSetsResponse.pb(return_value) + 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_expanded_data_sets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExpandedDataSetsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_expanded_data_sets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_expanded_data_sets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_expanded_data_sets] = mock_rpc + + request = {} + client.list_expanded_data_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_expanded_data_sets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_expanded_data_sets_rest_required_fields(request_type=analytics_admin.ListExpandedDataSetsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_expanded_data_sets._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_expanded_data_sets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListExpandedDataSetsResponse() + # 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 = analytics_admin.ListExpandedDataSetsResponse.pb(return_value) + 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_expanded_data_sets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_expanded_data_sets_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_expanded_data_sets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_expanded_data_sets_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_expanded_data_sets") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_expanded_data_sets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListExpandedDataSetsRequest.pb(analytics_admin.ListExpandedDataSetsRequest()) + 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 = analytics_admin.ListExpandedDataSetsResponse.to_json(analytics_admin.ListExpandedDataSetsResponse()) + + request = analytics_admin.ListExpandedDataSetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListExpandedDataSetsResponse() + + client.list_expanded_data_sets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_expanded_data_sets_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListExpandedDataSetsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_expanded_data_sets(request) + + +def test_list_expanded_data_sets_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListExpandedDataSetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListExpandedDataSetsResponse.pb(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_expanded_data_sets(**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/v1alpha/{parent=properties/*}/expandedDataSets" % client.transport._host, args[1]) + + +def test_list_expanded_data_sets_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_expanded_data_sets( + analytics_admin.ListExpandedDataSetsRequest(), + parent='parent_value', + ) + + +def test_list_expanded_data_sets_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='abc', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[], + next_page_token='def', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + ], + next_page_token='ghi', + ), + analytics_admin.ListExpandedDataSetsResponse( + expanded_data_sets=[ + expanded_data_set.ExpandedDataSet(), + expanded_data_set.ExpandedDataSet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListExpandedDataSetsResponse.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': 'properties/sample1'} + + pager = client.list_expanded_data_sets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, expanded_data_set.ExpandedDataSet) + for i in results) + + pages = list(client.list_expanded_data_sets(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", [ + analytics_admin.CreateExpandedDataSetRequest, + dict, +]) +def test_create_expanded_data_set_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["expanded_data_set"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'dimension_names': ['dimension_names_value1', 'dimension_names_value2'], 'metric_names': ['metric_names_value1', 'metric_names_value2'], 'dimension_filter_expression': {'and_group': {'filter_expressions': {}}, 'not_expression': {}, 'filter': {'string_filter': {'match_type': 1, 'value': 'value_value', 'case_sensitive': True}, 'in_list_filter': {'values': ['values_value1', 'values_value2'], 'case_sensitive': True}, 'field_name': 'field_name_value'}}, 'data_collection_start_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 = analytics_admin.CreateExpandedDataSetRequest.meta.fields["expanded_data_set"] + + 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["expanded_data_set"].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["expanded_data_set"][field])): + del request_init["expanded_data_set"][field][i][subfield] + else: + del request_init["expanded_data_set"][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 = gaa_expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_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 = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) + 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_expanded_data_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.dimension_names == ['dimension_names_value'] + assert response.metric_names == ['metric_names_value'] + +def test_create_expanded_data_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_expanded_data_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_expanded_data_set] = mock_rpc + + request = {} + client.create_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_expanded_data_set_rest_required_fields(request_type=analytics_admin.CreateExpandedDataSetRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_expanded_data_set._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_expanded_data_set._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gaa_expanded_data_set.ExpandedDataSet() + # 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 = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) + 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_expanded_data_set(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_expanded_data_set_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_expanded_data_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "expandedDataSet", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_expanded_data_set_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_expanded_data_set") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_expanded_data_set") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateExpandedDataSetRequest.pb(analytics_admin.CreateExpandedDataSetRequest()) + 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 = gaa_expanded_data_set.ExpandedDataSet.to_json(gaa_expanded_data_set.ExpandedDataSet()) + + request = analytics_admin.CreateExpandedDataSetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gaa_expanded_data_set.ExpandedDataSet() + + client.create_expanded_data_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_expanded_data_set_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateExpandedDataSetRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_expanded_data_set(request) + + +def test_create_expanded_data_set_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = gaa_expanded_data_set.ExpandedDataSet() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(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 = gaa_expanded_data_set.ExpandedDataSet.pb(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_expanded_data_set(**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/v1alpha/{parent=properties/*}/expandedDataSets" % client.transport._host, args[1]) + + +def test_create_expanded_data_set_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_expanded_data_set( + analytics_admin.CreateExpandedDataSetRequest(), + parent='parent_value', + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name='name_value'), + ) + + +def test_create_expanded_data_set_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateExpandedDataSetRequest, + dict, +]) +def test_update_expanded_data_set_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'expanded_data_set': {'name': 'properties/sample1/expandedDataSets/sample2'}} + request_init["expanded_data_set"] = {'name': 'properties/sample1/expandedDataSets/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'dimension_names': ['dimension_names_value1', 'dimension_names_value2'], 'metric_names': ['metric_names_value1', 'metric_names_value2'], 'dimension_filter_expression': {'and_group': {'filter_expressions': {}}, 'not_expression': {}, 'filter': {'string_filter': {'match_type': 1, 'value': 'value_value', 'case_sensitive': True}, 'in_list_filter': {'values': ['values_value1', 'values_value2'], 'case_sensitive': True}, 'field_name': 'field_name_value'}}, 'data_collection_start_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 = analytics_admin.UpdateExpandedDataSetRequest.meta.fields["expanded_data_set"] + + 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["expanded_data_set"].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["expanded_data_set"][field])): + del request_init["expanded_data_set"][field][i][subfield] + else: + del request_init["expanded_data_set"][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 = gaa_expanded_data_set.ExpandedDataSet( + name='name_value', + display_name='display_name_value', + description='description_value', + dimension_names=['dimension_names_value'], + metric_names=['metric_names_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 = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) + 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_expanded_data_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_expanded_data_set.ExpandedDataSet) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.dimension_names == ['dimension_names_value'] + assert response.metric_names == ['metric_names_value'] + +def test_update_expanded_data_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_expanded_data_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_expanded_data_set] = mock_rpc + + request = {} + client.update_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_expanded_data_set_rest_required_fields(request_type=analytics_admin.UpdateExpandedDataSetRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_expanded_data_set._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_expanded_data_set._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gaa_expanded_data_set.ExpandedDataSet() + # 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 = gaa_expanded_data_set.ExpandedDataSet.pb(return_value) + 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_expanded_data_set(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_expanded_data_set_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_expanded_data_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("expandedDataSet", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_expanded_data_set_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_expanded_data_set") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_expanded_data_set") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateExpandedDataSetRequest.pb(analytics_admin.UpdateExpandedDataSetRequest()) + 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 = gaa_expanded_data_set.ExpandedDataSet.to_json(gaa_expanded_data_set.ExpandedDataSet()) + + request = analytics_admin.UpdateExpandedDataSetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gaa_expanded_data_set.ExpandedDataSet() + + client.update_expanded_data_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_expanded_data_set_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateExpandedDataSetRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'expanded_data_set': {'name': 'properties/sample1/expandedDataSets/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_expanded_data_set(request) + + +def test_update_expanded_data_set_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = gaa_expanded_data_set.ExpandedDataSet() + + # get arguments that satisfy an http rule for this method + sample_request = {'expanded_data_set': {'name': 'properties/sample1/expandedDataSets/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(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 = gaa_expanded_data_set.ExpandedDataSet.pb(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_expanded_data_set(**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/v1alpha/{expanded_data_set.name=properties/*/expandedDataSets/*}" % client.transport._host, args[1]) + + +def test_update_expanded_data_set_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_expanded_data_set( + analytics_admin.UpdateExpandedDataSetRequest(), + expanded_data_set=gaa_expanded_data_set.ExpandedDataSet(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_expanded_data_set_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteExpandedDataSetRequest, + dict, +]) +def test_delete_expanded_data_set_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/expandedDataSets/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_expanded_data_set(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_expanded_data_set_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_expanded_data_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_expanded_data_set] = mock_rpc + + request = {} + client.delete_expanded_data_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_expanded_data_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_expanded_data_set_rest_required_fields(request_type=analytics_admin.DeleteExpandedDataSetRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_expanded_data_set._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_expanded_data_set._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 = AnalyticsAdminServiceClient( + 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_expanded_data_set(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_expanded_data_set_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_expanded_data_set._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_expanded_data_set_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_expanded_data_set") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteExpandedDataSetRequest.pb(analytics_admin.DeleteExpandedDataSetRequest()) + 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 = analytics_admin.DeleteExpandedDataSetRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_expanded_data_set(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_expanded_data_set_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteExpandedDataSetRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/expandedDataSets/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_expanded_data_set(request) + + +def test_delete_expanded_data_set_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/expandedDataSets/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_expanded_data_set(**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/v1alpha/{name=properties/*/expandedDataSets/*}" % client.transport._host, args[1]) + + +def test_delete_expanded_data_set_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_expanded_data_set( + analytics_admin.DeleteExpandedDataSetRequest(), + name='name_value', + ) + + +def test_delete_expanded_data_set_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetChannelGroupRequest, + dict, +]) +def test_get_channel_group_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/channelGroups/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 = channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=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 = channel_group.ChannelGroup.pb(return_value) + 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_channel_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, channel_group.ChannelGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.system_defined is True + assert response.primary is True + +def test_get_channel_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_channel_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_channel_group] = mock_rpc + + request = {} + client.get_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_channel_group_rest_required_fields(request_type=analytics_admin.GetChannelGroupRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_channel_group._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_channel_group._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = channel_group.ChannelGroup() + # 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 = channel_group.ChannelGroup.pb(return_value) + 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_channel_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_channel_group_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_channel_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_channel_group_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_channel_group") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_channel_group") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetChannelGroupRequest.pb(analytics_admin.GetChannelGroupRequest()) + 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 = channel_group.ChannelGroup.to_json(channel_group.ChannelGroup()) + + request = analytics_admin.GetChannelGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = channel_group.ChannelGroup() + + client.get_channel_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_channel_group_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetChannelGroupRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/channelGroups/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_channel_group(request) + + +def test_get_channel_group_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = channel_group.ChannelGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/channelGroups/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 = channel_group.ChannelGroup.pb(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_channel_group(**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/v1alpha/{name=properties/*/channelGroups/*}" % client.transport._host, args[1]) + + +def test_get_channel_group_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_channel_group( + analytics_admin.GetChannelGroupRequest(), + name='name_value', + ) + + +def test_get_channel_group_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListChannelGroupsRequest, + dict, +]) +def test_list_channel_groups_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListChannelGroupsResponse( + 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 = analytics_admin.ListChannelGroupsResponse.pb(return_value) + 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_channel_groups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChannelGroupsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_channel_groups_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_channel_groups in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_channel_groups] = mock_rpc + + request = {} + client.list_channel_groups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_channel_groups(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_channel_groups_rest_required_fields(request_type=analytics_admin.ListChannelGroupsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_channel_groups._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_channel_groups._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListChannelGroupsResponse() + # 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 = analytics_admin.ListChannelGroupsResponse.pb(return_value) + 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_channel_groups(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_channel_groups_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_channel_groups._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_channel_groups_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_channel_groups") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_channel_groups") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListChannelGroupsRequest.pb(analytics_admin.ListChannelGroupsRequest()) + 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 = analytics_admin.ListChannelGroupsResponse.to_json(analytics_admin.ListChannelGroupsResponse()) + + request = analytics_admin.ListChannelGroupsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListChannelGroupsResponse() + + client.list_channel_groups(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_channel_groups_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListChannelGroupsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_channel_groups(request) + + +def test_list_channel_groups_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListChannelGroupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListChannelGroupsResponse.pb(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_channel_groups(**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/v1alpha/{parent=properties/*}/channelGroups" % client.transport._host, args[1]) + + +def test_list_channel_groups_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_channel_groups( + analytics_admin.ListChannelGroupsRequest(), + parent='parent_value', + ) + + +def test_list_channel_groups_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + next_page_token='abc', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[], + next_page_token='def', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + ], + next_page_token='ghi', + ), + analytics_admin.ListChannelGroupsResponse( + channel_groups=[ + channel_group.ChannelGroup(), + channel_group.ChannelGroup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListChannelGroupsResponse.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': 'properties/sample1'} + + pager = client.list_channel_groups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, channel_group.ChannelGroup) + for i in results) + + pages = list(client.list_channel_groups(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", [ + analytics_admin.CreateChannelGroupRequest, + dict, +]) +def test_create_channel_group_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["channel_group"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'grouping_rule': [{'display_name': 'display_name_value', 'expression': {'and_group': {'filter_expressions': {}}, 'or_group': {}, 'not_expression': {}, 'filter': {'string_filter': {'match_type': 1, 'value': 'value_value'}, 'in_list_filter': {'values': ['values_value1', 'values_value2']}, 'field_name': 'field_name_value'}}}], 'system_defined': True, 'primary': 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 = analytics_admin.CreateChannelGroupRequest.meta.fields["channel_group"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["channel_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["channel_group"][field])): + del request_init["channel_group"][field][i][subfield] + else: + del request_init["channel_group"][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 = gaa_channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=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 = gaa_channel_group.ChannelGroup.pb(return_value) + 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_channel_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_channel_group.ChannelGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.system_defined is True + assert response.primary is True + +def test_create_channel_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_channel_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_channel_group] = mock_rpc + + request = {} + client.create_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_channel_group_rest_required_fields(request_type=analytics_admin.CreateChannelGroupRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_channel_group._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_channel_group._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gaa_channel_group.ChannelGroup() + # 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 = gaa_channel_group.ChannelGroup.pb(return_value) + 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_channel_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_channel_group_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_channel_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "channelGroup", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_channel_group_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_channel_group") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_channel_group") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateChannelGroupRequest.pb(analytics_admin.CreateChannelGroupRequest()) + 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 = gaa_channel_group.ChannelGroup.to_json(gaa_channel_group.ChannelGroup()) + + request = analytics_admin.CreateChannelGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gaa_channel_group.ChannelGroup() + + client.create_channel_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_channel_group_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateChannelGroupRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_channel_group(request) + + +def test_create_channel_group_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = gaa_channel_group.ChannelGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + channel_group=gaa_channel_group.ChannelGroup(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 = gaa_channel_group.ChannelGroup.pb(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_channel_group(**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/v1alpha/{parent=properties/*}/channelGroups" % client.transport._host, args[1]) + + +def test_create_channel_group_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_channel_group( + analytics_admin.CreateChannelGroupRequest(), + parent='parent_value', + channel_group=gaa_channel_group.ChannelGroup(name='name_value'), + ) + + +def test_create_channel_group_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateChannelGroupRequest, + dict, +]) +def test_update_channel_group_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'channel_group': {'name': 'properties/sample1/channelGroups/sample2'}} + request_init["channel_group"] = {'name': 'properties/sample1/channelGroups/sample2', 'display_name': 'display_name_value', 'description': 'description_value', 'grouping_rule': [{'display_name': 'display_name_value', 'expression': {'and_group': {'filter_expressions': {}}, 'or_group': {}, 'not_expression': {}, 'filter': {'string_filter': {'match_type': 1, 'value': 'value_value'}, 'in_list_filter': {'values': ['values_value1', 'values_value2']}, 'field_name': 'field_name_value'}}}], 'system_defined': True, 'primary': 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 = analytics_admin.UpdateChannelGroupRequest.meta.fields["channel_group"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["channel_group"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["channel_group"][field])): + del request_init["channel_group"][field][i][subfield] + else: + del request_init["channel_group"][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 = gaa_channel_group.ChannelGroup( + name='name_value', + display_name='display_name_value', + description='description_value', + system_defined=True, + primary=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 = gaa_channel_group.ChannelGroup.pb(return_value) + 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_channel_group(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_channel_group.ChannelGroup) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.system_defined is True + assert response.primary is True + +def test_update_channel_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_channel_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_channel_group] = mock_rpc + + request = {} + client.update_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_channel_group_rest_required_fields(request_type=analytics_admin.UpdateChannelGroupRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_channel_group._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_channel_group._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gaa_channel_group.ChannelGroup() + # 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 = gaa_channel_group.ChannelGroup.pb(return_value) + 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_channel_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_channel_group_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_channel_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("channelGroup", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_channel_group_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_channel_group") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_channel_group") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateChannelGroupRequest.pb(analytics_admin.UpdateChannelGroupRequest()) + 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 = gaa_channel_group.ChannelGroup.to_json(gaa_channel_group.ChannelGroup()) + + request = analytics_admin.UpdateChannelGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gaa_channel_group.ChannelGroup() + + client.update_channel_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_channel_group_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateChannelGroupRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'channel_group': {'name': 'properties/sample1/channelGroups/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_channel_group(request) + + +def test_update_channel_group_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = gaa_channel_group.ChannelGroup() + + # get arguments that satisfy an http rule for this method + sample_request = {'channel_group': {'name': 'properties/sample1/channelGroups/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + channel_group=gaa_channel_group.ChannelGroup(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 = gaa_channel_group.ChannelGroup.pb(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_channel_group(**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/v1alpha/{channel_group.name=properties/*/channelGroups/*}" % client.transport._host, args[1]) + + +def test_update_channel_group_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_channel_group( + analytics_admin.UpdateChannelGroupRequest(), + channel_group=gaa_channel_group.ChannelGroup(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_channel_group_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteChannelGroupRequest, + dict, +]) +def test_delete_channel_group_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/channelGroups/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_channel_group(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_channel_group_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_channel_group in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_channel_group] = mock_rpc + + request = {} + client.delete_channel_group(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_channel_group(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_channel_group_rest_required_fields(request_type=analytics_admin.DeleteChannelGroupRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_channel_group._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_channel_group._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 = AnalyticsAdminServiceClient( + 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_channel_group(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_channel_group_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_channel_group._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_channel_group_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_channel_group") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteChannelGroupRequest.pb(analytics_admin.DeleteChannelGroupRequest()) + 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 = analytics_admin.DeleteChannelGroupRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_channel_group(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_channel_group_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteChannelGroupRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/channelGroups/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_channel_group(request) + + +def test_delete_channel_group_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/channelGroups/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_channel_group(**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/v1alpha/{name=properties/*/channelGroups/*}" % client.transport._host, args[1]) + + +def test_delete_channel_group_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_channel_group( + analytics_admin.DeleteChannelGroupRequest(), + name='name_value', + ) + + +def test_delete_channel_group_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest, + dict, +]) +def test_set_automated_ga4_configuration_opt_out_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.pb(return_value) + 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_automated_ga4_configuration_opt_out(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse) + +def test_set_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.set_automated_ga4_configuration_opt_out in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.set_automated_ga4_configuration_opt_out] = mock_rpc + + request = {} + client.set_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.set_automated_ga4_configuration_opt_out(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_set_automated_ga4_configuration_opt_out_rest_required_fields(request_type=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["property"] = "" + 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_automated_ga4_configuration_opt_out._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["property"] = 'property_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).set_automated_ga4_configuration_opt_out._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "property" in jsonified_request + assert jsonified_request["property"] == 'property_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + # 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 = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.pb(return_value) + 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_automated_ga4_configuration_opt_out(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_set_automated_ga4_configuration_opt_out_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.set_automated_ga4_configuration_opt_out._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("property", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_automated_ga4_configuration_opt_out_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_set_automated_ga4_configuration_opt_out") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_set_automated_ga4_configuration_opt_out") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest.pb(analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest()) + 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 = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse.to_json(analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse()) + + request = analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.SetAutomatedGa4ConfigurationOptOutResponse() + + client.set_automated_ga4_configuration_opt_out(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_automated_ga4_configuration_opt_out_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.SetAutomatedGa4ConfigurationOptOutRequest): + client = AnalyticsAdminServiceClient( + 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_automated_ga4_configuration_opt_out(request) + + +def test_set_automated_ga4_configuration_opt_out_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest, + dict, +]) +def test_fetch_automated_ga4_configuration_opt_out_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse( + opt_out=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 = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.fetch_automated_ga4_configuration_opt_out(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse) + assert response.opt_out is True + +def test_fetch_automated_ga4_configuration_opt_out_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.fetch_automated_ga4_configuration_opt_out in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.fetch_automated_ga4_configuration_opt_out] = mock_rpc + + request = {} + client.fetch_automated_ga4_configuration_opt_out(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_automated_ga4_configuration_opt_out(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_fetch_automated_ga4_configuration_opt_out_rest_required_fields(request_type=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["property"] = "" + 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()).fetch_automated_ga4_configuration_opt_out._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["property"] = 'property_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_automated_ga4_configuration_opt_out._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "property" in jsonified_request + assert jsonified_request["property"] == 'property_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse() + # 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 = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.fetch_automated_ga4_configuration_opt_out(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_fetch_automated_ga4_configuration_opt_out_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.fetch_automated_ga4_configuration_opt_out._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("property", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_automated_ga4_configuration_opt_out_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_fetch_automated_ga4_configuration_opt_out") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_fetch_automated_ga4_configuration_opt_out") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest.pb(analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest()) + 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 = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse.to_json(analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse()) + + request = analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.FetchAutomatedGa4ConfigurationOptOutResponse() + + client.fetch_automated_ga4_configuration_opt_out(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_automated_ga4_configuration_opt_out_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.FetchAutomatedGa4ConfigurationOptOutRequest): + client = AnalyticsAdminServiceClient( + 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.fetch_automated_ga4_configuration_opt_out(request) + + +def test_fetch_automated_ga4_configuration_opt_out_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateBigQueryLinkRequest, + dict, +]) +def test_create_big_query_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["bigquery_link"] = {'name': 'name_value', 'project': 'project_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'daily_export_enabled': True, 'streaming_export_enabled': True, 'fresh_daily_export_enabled': True, 'include_advertising_id': True, 'export_streams': ['export_streams_value1', 'export_streams_value2'], 'excluded_events': ['excluded_events_value1', 'excluded_events_value2'], 'dataset_location': 'dataset_location_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 = analytics_admin.CreateBigQueryLinkRequest.meta.fields["bigquery_link"] + + 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["bigquery_link"].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["bigquery_link"][field])): + del request_init["bigquery_link"][field][i][subfield] + else: + del request_init["bigquery_link"][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 = resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_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 = resources.BigQueryLink.pb(return_value) + 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_big_query_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.BigQueryLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ['export_streams_value'] + assert response.excluded_events == ['excluded_events_value'] + assert response.dataset_location == 'dataset_location_value' + +def test_create_big_query_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_big_query_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_big_query_link] = mock_rpc + + request = {} + client.create_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_big_query_link_rest_required_fields(request_type=analytics_admin.CreateBigQueryLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_big_query_link._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_big_query_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.BigQueryLink() + # 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 = resources.BigQueryLink.pb(return_value) + 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_big_query_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_big_query_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_big_query_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "bigqueryLink", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_big_query_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_big_query_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_big_query_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateBigQueryLinkRequest.pb(analytics_admin.CreateBigQueryLinkRequest()) + 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 = resources.BigQueryLink.to_json(resources.BigQueryLink()) + + request = analytics_admin.CreateBigQueryLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.BigQueryLink() + + client.create_big_query_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_big_query_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateBigQueryLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_big_query_link(request) + + +def test_create_big_query_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.BigQueryLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + bigquery_link=resources.BigQueryLink(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 = resources.BigQueryLink.pb(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_big_query_link(**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/v1alpha/{parent=properties/*}/bigQueryLinks" % client.transport._host, args[1]) + + +def test_create_big_query_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_big_query_link( + analytics_admin.CreateBigQueryLinkRequest(), + parent='parent_value', + bigquery_link=resources.BigQueryLink(name='name_value'), + ) + + +def test_create_big_query_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetBigQueryLinkRequest, + dict, +]) +def test_get_big_query_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/bigQueryLinks/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 = resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_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 = resources.BigQueryLink.pb(return_value) + 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_big_query_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.BigQueryLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ['export_streams_value'] + assert response.excluded_events == ['excluded_events_value'] + assert response.dataset_location == 'dataset_location_value' + +def test_get_big_query_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_big_query_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_big_query_link] = mock_rpc + + request = {} + client.get_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_big_query_link_rest_required_fields(request_type=analytics_admin.GetBigQueryLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_big_query_link._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_big_query_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.BigQueryLink() + # 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 = resources.BigQueryLink.pb(return_value) + 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_big_query_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_big_query_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_big_query_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_big_query_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_big_query_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_big_query_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetBigQueryLinkRequest.pb(analytics_admin.GetBigQueryLinkRequest()) + 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 = resources.BigQueryLink.to_json(resources.BigQueryLink()) + + request = analytics_admin.GetBigQueryLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.BigQueryLink() + + client.get_big_query_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_big_query_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetBigQueryLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/bigQueryLinks/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_big_query_link(request) + + +def test_get_big_query_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.BigQueryLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/bigQueryLinks/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 = resources.BigQueryLink.pb(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_big_query_link(**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/v1alpha/{name=properties/*/bigQueryLinks/*}" % client.transport._host, args[1]) + + +def test_get_big_query_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_big_query_link( + analytics_admin.GetBigQueryLinkRequest(), + name='name_value', + ) + + +def test_get_big_query_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListBigQueryLinksRequest, + dict, +]) +def test_list_big_query_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListBigQueryLinksResponse( + 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 = analytics_admin.ListBigQueryLinksResponse.pb(return_value) + 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_big_query_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBigQueryLinksPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_big_query_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_big_query_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_big_query_links] = mock_rpc + + request = {} + client.list_big_query_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_big_query_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_big_query_links_rest_required_fields(request_type=analytics_admin.ListBigQueryLinksRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_big_query_links._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_big_query_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListBigQueryLinksResponse() + # 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 = analytics_admin.ListBigQueryLinksResponse.pb(return_value) + 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_big_query_links(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_big_query_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_big_query_links._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_big_query_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_big_query_links") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_big_query_links") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListBigQueryLinksRequest.pb(analytics_admin.ListBigQueryLinksRequest()) + 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 = analytics_admin.ListBigQueryLinksResponse.to_json(analytics_admin.ListBigQueryLinksResponse()) + + request = analytics_admin.ListBigQueryLinksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListBigQueryLinksResponse() + + client.list_big_query_links(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_big_query_links_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListBigQueryLinksRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_big_query_links(request) + + +def test_list_big_query_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListBigQueryLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListBigQueryLinksResponse.pb(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_big_query_links(**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/v1alpha/{parent=properties/*}/bigQueryLinks" % client.transport._host, args[1]) + + +def test_list_big_query_links_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_big_query_links( + analytics_admin.ListBigQueryLinksRequest(), + parent='parent_value', + ) + + +def test_list_big_query_links_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[], + next_page_token='def', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListBigQueryLinksResponse( + bigquery_links=[ + resources.BigQueryLink(), + resources.BigQueryLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListBigQueryLinksResponse.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': 'properties/sample1'} + + pager = client.list_big_query_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.BigQueryLink) + for i in results) + + pages = list(client.list_big_query_links(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", [ + analytics_admin.DeleteBigQueryLinkRequest, + dict, +]) +def test_delete_big_query_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/bigQueryLinks/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_big_query_link(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_big_query_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_big_query_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_big_query_link] = mock_rpc + + request = {} + client.delete_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_big_query_link_rest_required_fields(request_type=analytics_admin.DeleteBigQueryLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_big_query_link._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_big_query_link._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 = AnalyticsAdminServiceClient( + 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_big_query_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_big_query_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_big_query_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_big_query_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_big_query_link") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteBigQueryLinkRequest.pb(analytics_admin.DeleteBigQueryLinkRequest()) + 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 = analytics_admin.DeleteBigQueryLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_big_query_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_big_query_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteBigQueryLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/bigQueryLinks/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_big_query_link(request) + + +def test_delete_big_query_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/bigQueryLinks/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_big_query_link(**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/v1alpha/{name=properties/*/bigQueryLinks/*}" % client.transport._host, args[1]) + + +def test_delete_big_query_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_big_query_link( + analytics_admin.DeleteBigQueryLinkRequest(), + name='name_value', + ) + + +def test_delete_big_query_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateBigQueryLinkRequest, + dict, +]) +def test_update_big_query_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'bigquery_link': {'name': 'properties/sample1/bigQueryLinks/sample2'}} + request_init["bigquery_link"] = {'name': 'properties/sample1/bigQueryLinks/sample2', 'project': 'project_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'daily_export_enabled': True, 'streaming_export_enabled': True, 'fresh_daily_export_enabled': True, 'include_advertising_id': True, 'export_streams': ['export_streams_value1', 'export_streams_value2'], 'excluded_events': ['excluded_events_value1', 'excluded_events_value2'], 'dataset_location': 'dataset_location_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 = analytics_admin.UpdateBigQueryLinkRequest.meta.fields["bigquery_link"] + + 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["bigquery_link"].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["bigquery_link"][field])): + del request_init["bigquery_link"][field][i][subfield] + else: + del request_init["bigquery_link"][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 = resources.BigQueryLink( + name='name_value', + project='project_value', + daily_export_enabled=True, + streaming_export_enabled=True, + fresh_daily_export_enabled=True, + include_advertising_id=True, + export_streams=['export_streams_value'], + excluded_events=['excluded_events_value'], + dataset_location='dataset_location_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 = resources.BigQueryLink.pb(return_value) + 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_big_query_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.BigQueryLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + assert response.daily_export_enabled is True + assert response.streaming_export_enabled is True + assert response.fresh_daily_export_enabled is True + assert response.include_advertising_id is True + assert response.export_streams == ['export_streams_value'] + assert response.excluded_events == ['excluded_events_value'] + assert response.dataset_location == 'dataset_location_value' + +def test_update_big_query_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_big_query_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_big_query_link] = mock_rpc + + request = {} + client.update_big_query_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_big_query_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_big_query_link_rest_required_fields(request_type=analytics_admin.UpdateBigQueryLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_big_query_link._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_big_query_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.BigQueryLink() + # 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 = resources.BigQueryLink.pb(return_value) + 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_big_query_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_big_query_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_big_query_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("bigqueryLink", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_big_query_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_big_query_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_big_query_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateBigQueryLinkRequest.pb(analytics_admin.UpdateBigQueryLinkRequest()) + 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 = resources.BigQueryLink.to_json(resources.BigQueryLink()) + + request = analytics_admin.UpdateBigQueryLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.BigQueryLink() + + client.update_big_query_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_big_query_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateBigQueryLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'bigquery_link': {'name': 'properties/sample1/bigQueryLinks/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_big_query_link(request) + + +def test_update_big_query_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.BigQueryLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'bigquery_link': {'name': 'properties/sample1/bigQueryLinks/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + bigquery_link=resources.BigQueryLink(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 = resources.BigQueryLink.pb(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_big_query_link(**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/v1alpha/{bigquery_link.name=properties/*/bigQueryLinks/*}" % client.transport._host, args[1]) + + +def test_update_big_query_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_big_query_link( + analytics_admin.UpdateBigQueryLinkRequest(), + bigquery_link=resources.BigQueryLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_big_query_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetEnhancedMeasurementSettingsRequest, + dict, +]) +def test_get_enhanced_measurement_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/enhancedMeasurementSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.EnhancedMeasurementSettings( + name='name_value', + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter='search_query_parameter_value', + uri_query_parameter='uri_query_parameter_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 = resources.EnhancedMeasurementSettings.pb(return_value) + 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_enhanced_measurement_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == 'name_value' + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == 'search_query_parameter_value' + assert response.uri_query_parameter == 'uri_query_parameter_value' + +def test_get_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_enhanced_measurement_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_enhanced_measurement_settings] = mock_rpc + + request = {} + client.get_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_enhanced_measurement_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_enhanced_measurement_settings_rest_required_fields(request_type=analytics_admin.GetEnhancedMeasurementSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_enhanced_measurement_settings._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_enhanced_measurement_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.EnhancedMeasurementSettings() + # 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 = resources.EnhancedMeasurementSettings.pb(return_value) + 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_enhanced_measurement_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_enhanced_measurement_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_enhanced_measurement_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_enhanced_measurement_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_enhanced_measurement_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_enhanced_measurement_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetEnhancedMeasurementSettingsRequest.pb(analytics_admin.GetEnhancedMeasurementSettingsRequest()) + 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 = resources.EnhancedMeasurementSettings.to_json(resources.EnhancedMeasurementSettings()) + + request = analytics_admin.GetEnhancedMeasurementSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.EnhancedMeasurementSettings() + + client.get_enhanced_measurement_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_enhanced_measurement_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetEnhancedMeasurementSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/enhancedMeasurementSettings'} + 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_enhanced_measurement_settings(request) + + +def test_get_enhanced_measurement_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.EnhancedMeasurementSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/sample2/enhancedMeasurementSettings'} + + # 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 = resources.EnhancedMeasurementSettings.pb(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_enhanced_measurement_settings(**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/v1alpha/{name=properties/*/dataStreams/*/enhancedMeasurementSettings}" % client.transport._host, args[1]) + + +def test_get_enhanced_measurement_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_enhanced_measurement_settings( + analytics_admin.GetEnhancedMeasurementSettingsRequest(), + name='name_value', + ) + + +def test_get_enhanced_measurement_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateEnhancedMeasurementSettingsRequest, + dict, +]) +def test_update_enhanced_measurement_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'enhanced_measurement_settings': {'name': 'properties/sample1/dataStreams/sample2/enhancedMeasurementSettings'}} + request_init["enhanced_measurement_settings"] = {'name': 'properties/sample1/dataStreams/sample2/enhancedMeasurementSettings', 'stream_enabled': True, 'scrolls_enabled': True, 'outbound_clicks_enabled': True, 'site_search_enabled': True, 'video_engagement_enabled': True, 'file_downloads_enabled': True, 'page_changes_enabled': True, 'form_interactions_enabled': True, 'search_query_parameter': 'search_query_parameter_value', 'uri_query_parameter': 'uri_query_parameter_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 = analytics_admin.UpdateEnhancedMeasurementSettingsRequest.meta.fields["enhanced_measurement_settings"] + + 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["enhanced_measurement_settings"].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["enhanced_measurement_settings"][field])): + del request_init["enhanced_measurement_settings"][field][i][subfield] + else: + del request_init["enhanced_measurement_settings"][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 = resources.EnhancedMeasurementSettings( + name='name_value', + stream_enabled=True, + scrolls_enabled=True, + outbound_clicks_enabled=True, + site_search_enabled=True, + video_engagement_enabled=True, + file_downloads_enabled=True, + page_changes_enabled=True, + form_interactions_enabled=True, + search_query_parameter='search_query_parameter_value', + uri_query_parameter='uri_query_parameter_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 = resources.EnhancedMeasurementSettings.pb(return_value) + 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_enhanced_measurement_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.EnhancedMeasurementSettings) + assert response.name == 'name_value' + assert response.stream_enabled is True + assert response.scrolls_enabled is True + assert response.outbound_clicks_enabled is True + assert response.site_search_enabled is True + assert response.video_engagement_enabled is True + assert response.file_downloads_enabled is True + assert response.page_changes_enabled is True + assert response.form_interactions_enabled is True + assert response.search_query_parameter == 'search_query_parameter_value' + assert response.uri_query_parameter == 'uri_query_parameter_value' + +def test_update_enhanced_measurement_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_enhanced_measurement_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_enhanced_measurement_settings] = mock_rpc + + request = {} + client.update_enhanced_measurement_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_enhanced_measurement_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_enhanced_measurement_settings_rest_required_fields(request_type=analytics_admin.UpdateEnhancedMeasurementSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_enhanced_measurement_settings._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_enhanced_measurement_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.EnhancedMeasurementSettings() + # 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 = resources.EnhancedMeasurementSettings.pb(return_value) + 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_enhanced_measurement_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_enhanced_measurement_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_enhanced_measurement_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("enhancedMeasurementSettings", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_enhanced_measurement_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_enhanced_measurement_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_enhanced_measurement_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateEnhancedMeasurementSettingsRequest.pb(analytics_admin.UpdateEnhancedMeasurementSettingsRequest()) + 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 = resources.EnhancedMeasurementSettings.to_json(resources.EnhancedMeasurementSettings()) + + request = analytics_admin.UpdateEnhancedMeasurementSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.EnhancedMeasurementSettings() + + client.update_enhanced_measurement_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_enhanced_measurement_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateEnhancedMeasurementSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'enhanced_measurement_settings': {'name': 'properties/sample1/dataStreams/sample2/enhancedMeasurementSettings'}} + 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_enhanced_measurement_settings(request) + + +def test_update_enhanced_measurement_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.EnhancedMeasurementSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'enhanced_measurement_settings': {'name': 'properties/sample1/dataStreams/sample2/enhancedMeasurementSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + enhanced_measurement_settings=resources.EnhancedMeasurementSettings(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 = resources.EnhancedMeasurementSettings.pb(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_enhanced_measurement_settings(**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/v1alpha/{enhanced_measurement_settings.name=properties/*/dataStreams/*/enhancedMeasurementSettings}" % client.transport._host, args[1]) + + +def test_update_enhanced_measurement_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_enhanced_measurement_settings( + analytics_admin.UpdateEnhancedMeasurementSettingsRequest(), + enhanced_measurement_settings=resources.EnhancedMeasurementSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_enhanced_measurement_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateConnectedSiteTagRequest, + dict, +]) +def test_create_connected_site_tag_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateConnectedSiteTagResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.CreateConnectedSiteTagResponse.pb(return_value) + 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_connected_site_tag(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.CreateConnectedSiteTagResponse) + +def test_create_connected_site_tag_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_connected_site_tag in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_connected_site_tag] = mock_rpc + + request = {} + client.create_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_connected_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_connected_site_tag_rest_required_fields(request_type=analytics_admin.CreateConnectedSiteTagRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_connected_site_tag._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_connected_site_tag._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.CreateConnectedSiteTagResponse() + # 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 = analytics_admin.CreateConnectedSiteTagResponse.pb(return_value) + 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_connected_site_tag(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_connected_site_tag_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_connected_site_tag._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("connectedSiteTag", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_connected_site_tag_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_connected_site_tag") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_connected_site_tag") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateConnectedSiteTagRequest.pb(analytics_admin.CreateConnectedSiteTagRequest()) + 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 = analytics_admin.CreateConnectedSiteTagResponse.to_json(analytics_admin.CreateConnectedSiteTagResponse()) + + request = analytics_admin.CreateConnectedSiteTagRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.CreateConnectedSiteTagResponse() + + client.create_connected_site_tag(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_connected_site_tag_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateConnectedSiteTagRequest): + client = AnalyticsAdminServiceClient( + 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_connected_site_tag(request) + + +def test_create_connected_site_tag_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteConnectedSiteTagRequest, + dict, +]) +def test_delete_connected_site_tag_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = 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_connected_site_tag(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_connected_site_tag_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_connected_site_tag in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_connected_site_tag] = mock_rpc + + request = {} + client.delete_connected_site_tag(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_connected_site_tag(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_connected_site_tag_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_connected_site_tag") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteConnectedSiteTagRequest.pb(analytics_admin.DeleteConnectedSiteTagRequest()) + 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 = analytics_admin.DeleteConnectedSiteTagRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_connected_site_tag(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_connected_site_tag_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteConnectedSiteTagRequest): + client = AnalyticsAdminServiceClient( + 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.delete_connected_site_tag(request) + + +def test_delete_connected_site_tag_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListConnectedSiteTagsRequest, + dict, +]) +def test_list_connected_site_tags_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListConnectedSiteTagsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ListConnectedSiteTagsResponse.pb(return_value) + 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_connected_site_tags(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ListConnectedSiteTagsResponse) + +def test_list_connected_site_tags_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_connected_site_tags in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_connected_site_tags] = mock_rpc + + request = {} + client.list_connected_site_tags(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_connected_site_tags(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_connected_site_tags_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_connected_site_tags") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_connected_site_tags") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListConnectedSiteTagsRequest.pb(analytics_admin.ListConnectedSiteTagsRequest()) + 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 = analytics_admin.ListConnectedSiteTagsResponse.to_json(analytics_admin.ListConnectedSiteTagsResponse()) + + request = analytics_admin.ListConnectedSiteTagsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListConnectedSiteTagsResponse() + + client.list_connected_site_tags(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_connected_site_tags_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListConnectedSiteTagsRequest): + client = AnalyticsAdminServiceClient( + 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_connected_site_tags(request) + + +def test_list_connected_site_tags_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.FetchConnectedGa4PropertyRequest, + dict, +]) +def test_fetch_connected_ga4_property_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.FetchConnectedGa4PropertyResponse( + property='property_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 = analytics_admin.FetchConnectedGa4PropertyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.fetch_connected_ga4_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.FetchConnectedGa4PropertyResponse) + assert response.property == 'property_value' + +def test_fetch_connected_ga4_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.fetch_connected_ga4_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.fetch_connected_ga4_property] = mock_rpc + + request = {} + client.fetch_connected_ga4_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_connected_ga4_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_fetch_connected_ga4_property_rest_required_fields(request_type=analytics_admin.FetchConnectedGa4PropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["property"] = "" + 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 "property" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_connected_ga4_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "property" in jsonified_request + assert jsonified_request["property"] == request_init["property"] + + jsonified_request["property"] = 'property_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).fetch_connected_ga4_property._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("property", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "property" in jsonified_request + assert jsonified_request["property"] == 'property_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.FetchConnectedGa4PropertyResponse() + # 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 = analytics_admin.FetchConnectedGa4PropertyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.fetch_connected_ga4_property(request) + + expected_params = [ + ( + "property", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_fetch_connected_ga4_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.fetch_connected_ga4_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(("property", )) & set(("property", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_connected_ga4_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_fetch_connected_ga4_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_fetch_connected_ga4_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.FetchConnectedGa4PropertyRequest.pb(analytics_admin.FetchConnectedGa4PropertyRequest()) + 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 = analytics_admin.FetchConnectedGa4PropertyResponse.to_json(analytics_admin.FetchConnectedGa4PropertyResponse()) + + request = analytics_admin.FetchConnectedGa4PropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.FetchConnectedGa4PropertyResponse() + + client.fetch_connected_ga4_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_fetch_connected_ga4_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.FetchConnectedGa4PropertyRequest): + client = AnalyticsAdminServiceClient( + 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.fetch_connected_ga4_property(request) + + +def test_fetch_connected_ga4_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAdSenseLinkRequest, + dict, +]) +def test_get_ad_sense_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/adSenseLinks/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 = resources.AdSenseLink( + name='name_value', + ad_client_code='ad_client_code_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 = resources.AdSenseLink.pb(return_value) + 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_ad_sense_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdSenseLink) + assert response.name == 'name_value' + assert response.ad_client_code == 'ad_client_code_value' + +def test_get_ad_sense_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_ad_sense_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_ad_sense_link] = mock_rpc + + request = {} + client.get_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_ad_sense_link_rest_required_fields(request_type=analytics_admin.GetAdSenseLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_ad_sense_link._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_ad_sense_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AdSenseLink() + # 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 = resources.AdSenseLink.pb(return_value) + 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_ad_sense_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_ad_sense_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_ad_sense_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_ad_sense_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_ad_sense_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_ad_sense_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetAdSenseLinkRequest.pb(analytics_admin.GetAdSenseLinkRequest()) + 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 = resources.AdSenseLink.to_json(resources.AdSenseLink()) + + request = analytics_admin.GetAdSenseLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.AdSenseLink() + + client.get_ad_sense_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_ad_sense_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetAdSenseLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/adSenseLinks/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_ad_sense_link(request) + + +def test_get_ad_sense_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.AdSenseLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/adSenseLinks/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 = resources.AdSenseLink.pb(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_ad_sense_link(**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/v1alpha/{name=properties/*/adSenseLinks/*}" % client.transport._host, args[1]) + + +def test_get_ad_sense_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_ad_sense_link( + analytics_admin.GetAdSenseLinkRequest(), + name='name_value', + ) + + +def test_get_ad_sense_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateAdSenseLinkRequest, + dict, +]) +def test_create_ad_sense_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["adsense_link"] = {'name': 'name_value', 'ad_client_code': 'ad_client_code_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 = analytics_admin.CreateAdSenseLinkRequest.meta.fields["adsense_link"] + + 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["adsense_link"].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["adsense_link"][field])): + del request_init["adsense_link"][field][i][subfield] + else: + del request_init["adsense_link"][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 = resources.AdSenseLink( + name='name_value', + ad_client_code='ad_client_code_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 = resources.AdSenseLink.pb(return_value) + 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_ad_sense_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.AdSenseLink) + assert response.name == 'name_value' + assert response.ad_client_code == 'ad_client_code_value' + +def test_create_ad_sense_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_ad_sense_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_ad_sense_link] = mock_rpc + + request = {} + client.create_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_ad_sense_link_rest_required_fields(request_type=analytics_admin.CreateAdSenseLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_ad_sense_link._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_ad_sense_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.AdSenseLink() + # 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 = resources.AdSenseLink.pb(return_value) + 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_ad_sense_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_ad_sense_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_ad_sense_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "adsenseLink", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_ad_sense_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_ad_sense_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_ad_sense_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateAdSenseLinkRequest.pb(analytics_admin.CreateAdSenseLinkRequest()) + 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 = resources.AdSenseLink.to_json(resources.AdSenseLink()) + + request = analytics_admin.CreateAdSenseLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.AdSenseLink() + + client.create_ad_sense_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_ad_sense_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateAdSenseLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_ad_sense_link(request) + + +def test_create_ad_sense_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.AdSenseLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + adsense_link=resources.AdSenseLink(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 = resources.AdSenseLink.pb(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_ad_sense_link(**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/v1alpha/{parent=properties/*}/adSenseLinks" % client.transport._host, args[1]) + + +def test_create_ad_sense_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_ad_sense_link( + analytics_admin.CreateAdSenseLinkRequest(), + parent='parent_value', + adsense_link=resources.AdSenseLink(name='name_value'), + ) + + +def test_create_ad_sense_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteAdSenseLinkRequest, + dict, +]) +def test_delete_ad_sense_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/adSenseLinks/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_ad_sense_link(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_ad_sense_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_ad_sense_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_ad_sense_link] = mock_rpc + + request = {} + client.delete_ad_sense_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_ad_sense_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_ad_sense_link_rest_required_fields(request_type=analytics_admin.DeleteAdSenseLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_ad_sense_link._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_ad_sense_link._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 = AnalyticsAdminServiceClient( + 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_ad_sense_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_ad_sense_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_ad_sense_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_ad_sense_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_ad_sense_link") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteAdSenseLinkRequest.pb(analytics_admin.DeleteAdSenseLinkRequest()) + 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 = analytics_admin.DeleteAdSenseLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_ad_sense_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_ad_sense_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteAdSenseLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/adSenseLinks/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_ad_sense_link(request) + + +def test_delete_ad_sense_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/adSenseLinks/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_ad_sense_link(**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/v1alpha/{name=properties/*/adSenseLinks/*}" % client.transport._host, args[1]) + + +def test_delete_ad_sense_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_ad_sense_link( + analytics_admin.DeleteAdSenseLinkRequest(), + name='name_value', + ) + + +def test_delete_ad_sense_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAdSenseLinksRequest, + dict, +]) +def test_list_ad_sense_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListAdSenseLinksResponse( + 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 = analytics_admin.ListAdSenseLinksResponse.pb(return_value) + 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_ad_sense_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAdSenseLinksPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_ad_sense_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_ad_sense_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_ad_sense_links] = mock_rpc + + request = {} + client.list_ad_sense_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_ad_sense_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_ad_sense_links_rest_required_fields(request_type=analytics_admin.ListAdSenseLinksRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_ad_sense_links._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_ad_sense_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListAdSenseLinksResponse() + # 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 = analytics_admin.ListAdSenseLinksResponse.pb(return_value) + 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_ad_sense_links(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_ad_sense_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_ad_sense_links._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_ad_sense_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_ad_sense_links") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_ad_sense_links") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListAdSenseLinksRequest.pb(analytics_admin.ListAdSenseLinksRequest()) + 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 = analytics_admin.ListAdSenseLinksResponse.to_json(analytics_admin.ListAdSenseLinksResponse()) + + request = analytics_admin.ListAdSenseLinksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListAdSenseLinksResponse() + + client.list_ad_sense_links(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_ad_sense_links_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListAdSenseLinksRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_ad_sense_links(request) + + +def test_list_ad_sense_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAdSenseLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListAdSenseLinksResponse.pb(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_ad_sense_links(**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/v1alpha/{parent=properties/*}/adSenseLinks" % client.transport._host, args[1]) + + +def test_list_ad_sense_links_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_ad_sense_links( + analytics_admin.ListAdSenseLinksRequest(), + parent='parent_value', + ) + + +def test_list_ad_sense_links_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[], + next_page_token='def', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAdSenseLinksResponse( + adsense_links=[ + resources.AdSenseLink(), + resources.AdSenseLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListAdSenseLinksResponse.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': 'properties/sample1'} + + pager = client.list_ad_sense_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AdSenseLink) + for i in results) + + pages = list(client.list_ad_sense_links(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", [ + analytics_admin.GetEventCreateRuleRequest, + dict, +]) +def test_get_event_create_rule_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/eventCreateRules/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 = event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=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 = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_event_create_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == 'name_value' + assert response.destination_event == 'destination_event_value' + assert response.source_copy_parameters is True + +def test_get_event_create_rule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event_create_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event_create_rule] = mock_rpc + + request = {} + client.get_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_event_create_rule_rest_required_fields(request_type=analytics_admin.GetEventCreateRuleRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_event_create_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_event_create_rule._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = event_create_and_edit.EventCreateRule() + # 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 = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_event_create_rule(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_event_create_rule_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_event_create_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_event_create_rule_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_event_create_rule") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_event_create_rule") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetEventCreateRuleRequest.pb(analytics_admin.GetEventCreateRuleRequest()) + 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 = event_create_and_edit.EventCreateRule.to_json(event_create_and_edit.EventCreateRule()) + + request = analytics_admin.GetEventCreateRuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = event_create_and_edit.EventCreateRule() + + client.get_event_create_rule(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_event_create_rule_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetEventCreateRuleRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/eventCreateRules/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_event_create_rule(request) + + +def test_get_event_create_rule_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = event_create_and_edit.EventCreateRule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/sample2/eventCreateRules/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 = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_event_create_rule(**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/v1alpha/{name=properties/*/dataStreams/*/eventCreateRules/*}" % client.transport._host, args[1]) + + +def test_get_event_create_rule_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_event_create_rule( + analytics_admin.GetEventCreateRuleRequest(), + name='name_value', + ) + + +def test_get_event_create_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListEventCreateRulesRequest, + dict, +]) +def test_list_event_create_rules_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListEventCreateRulesResponse( + 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 = analytics_admin.ListEventCreateRulesResponse.pb(return_value) + 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_event_create_rules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventCreateRulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_event_create_rules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_event_create_rules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_event_create_rules] = mock_rpc + + request = {} + client.list_event_create_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_event_create_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_event_create_rules_rest_required_fields(request_type=analytics_admin.ListEventCreateRulesRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_event_create_rules._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_event_create_rules._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListEventCreateRulesResponse() + # 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 = analytics_admin.ListEventCreateRulesResponse.pb(return_value) + 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_event_create_rules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_event_create_rules_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_event_create_rules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_event_create_rules_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_event_create_rules") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_event_create_rules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListEventCreateRulesRequest.pb(analytics_admin.ListEventCreateRulesRequest()) + 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 = analytics_admin.ListEventCreateRulesResponse.to_json(analytics_admin.ListEventCreateRulesResponse()) + + request = analytics_admin.ListEventCreateRulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListEventCreateRulesResponse() + + client.list_event_create_rules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_event_create_rules_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListEventCreateRulesRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_event_create_rules(request) + + +def test_list_event_create_rules_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListEventCreateRulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListEventCreateRulesResponse.pb(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_event_create_rules(**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/v1alpha/{parent=properties/*/dataStreams/*}/eventCreateRules" % client.transport._host, args[1]) + + +def test_list_event_create_rules_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_event_create_rules( + analytics_admin.ListEventCreateRulesRequest(), + parent='parent_value', + ) + + +def test_list_event_create_rules_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventCreateRulesResponse( + event_create_rules=[ + event_create_and_edit.EventCreateRule(), + event_create_and_edit.EventCreateRule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListEventCreateRulesResponse.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': 'properties/sample1/dataStreams/sample2'} + + pager = client.list_event_create_rules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, event_create_and_edit.EventCreateRule) + for i in results) + + pages = list(client.list_event_create_rules(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", [ + analytics_admin.CreateEventCreateRuleRequest, + dict, +]) +def test_create_event_create_rule_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/sample2'} + request_init["event_create_rule"] = {'name': 'name_value', 'destination_event': 'destination_event_value', 'event_conditions': [{'field': 'field_value', 'comparison_type': 1, 'value': 'value_value', 'negated': True}], 'source_copy_parameters': True, 'parameter_mutations': [{'parameter': 'parameter_value', 'parameter_value': 'parameter_value_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 = analytics_admin.CreateEventCreateRuleRequest.meta.fields["event_create_rule"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event_create_rule"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event_create_rule"][field])): + del request_init["event_create_rule"][field][i][subfield] + else: + del request_init["event_create_rule"][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 = event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=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 = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_event_create_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == 'name_value' + assert response.destination_event == 'destination_event_value' + assert response.source_copy_parameters is True + +def test_create_event_create_rule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_event_create_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_event_create_rule] = mock_rpc + + request = {} + client.create_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_event_create_rule_rest_required_fields(request_type=analytics_admin.CreateEventCreateRuleRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_event_create_rule._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_event_create_rule._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = event_create_and_edit.EventCreateRule() + # 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 = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_event_create_rule(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_event_create_rule_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_event_create_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "eventCreateRule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_event_create_rule_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_event_create_rule") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_event_create_rule") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateEventCreateRuleRequest.pb(analytics_admin.CreateEventCreateRuleRequest()) + 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 = event_create_and_edit.EventCreateRule.to_json(event_create_and_edit.EventCreateRule()) + + request = analytics_admin.CreateEventCreateRuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = event_create_and_edit.EventCreateRule() + + client.create_event_create_rule(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_event_create_rule_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateEventCreateRuleRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_event_create_rule(request) + + +def test_create_event_create_rule_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = event_create_and_edit.EventCreateRule() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + event_create_rule=event_create_and_edit.EventCreateRule(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 = event_create_and_edit.EventCreateRule.pb(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_event_create_rule(**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/v1alpha/{parent=properties/*/dataStreams/*}/eventCreateRules" % client.transport._host, args[1]) + + +def test_create_event_create_rule_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_event_create_rule( + analytics_admin.CreateEventCreateRuleRequest(), + parent='parent_value', + event_create_rule=event_create_and_edit.EventCreateRule(name='name_value'), + ) + + +def test_create_event_create_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateEventCreateRuleRequest, + dict, +]) +def test_update_event_create_rule_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'event_create_rule': {'name': 'properties/sample1/dataStreams/sample2/eventCreateRules/sample3'}} + request_init["event_create_rule"] = {'name': 'properties/sample1/dataStreams/sample2/eventCreateRules/sample3', 'destination_event': 'destination_event_value', 'event_conditions': [{'field': 'field_value', 'comparison_type': 1, 'value': 'value_value', 'negated': True}], 'source_copy_parameters': True, 'parameter_mutations': [{'parameter': 'parameter_value', 'parameter_value': 'parameter_value_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 = analytics_admin.UpdateEventCreateRuleRequest.meta.fields["event_create_rule"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event_create_rule"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event_create_rule"][field])): + del request_init["event_create_rule"][field][i][subfield] + else: + del request_init["event_create_rule"][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 = event_create_and_edit.EventCreateRule( + name='name_value', + destination_event='destination_event_value', + source_copy_parameters=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 = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_event_create_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventCreateRule) + assert response.name == 'name_value' + assert response.destination_event == 'destination_event_value' + assert response.source_copy_parameters is True + +def test_update_event_create_rule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_event_create_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event_create_rule] = mock_rpc + + request = {} + client.update_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_event_create_rule_rest_required_fields(request_type=analytics_admin.UpdateEventCreateRuleRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_event_create_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_event_create_rule._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = event_create_and_edit.EventCreateRule() + # 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 = event_create_and_edit.EventCreateRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_event_create_rule(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_event_create_rule_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_event_create_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("eventCreateRule", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_event_create_rule_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_event_create_rule") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_event_create_rule") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateEventCreateRuleRequest.pb(analytics_admin.UpdateEventCreateRuleRequest()) + 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 = event_create_and_edit.EventCreateRule.to_json(event_create_and_edit.EventCreateRule()) + + request = analytics_admin.UpdateEventCreateRuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = event_create_and_edit.EventCreateRule() + + client.update_event_create_rule(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_event_create_rule_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateEventCreateRuleRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'event_create_rule': {'name': 'properties/sample1/dataStreams/sample2/eventCreateRules/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_event_create_rule(request) + + +def test_update_event_create_rule_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = event_create_and_edit.EventCreateRule() + + # get arguments that satisfy an http rule for this method + sample_request = {'event_create_rule': {'name': 'properties/sample1/dataStreams/sample2/eventCreateRules/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + event_create_rule=event_create_and_edit.EventCreateRule(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 = event_create_and_edit.EventCreateRule.pb(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_event_create_rule(**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/v1alpha/{event_create_rule.name=properties/*/dataStreams/*/eventCreateRules/*}" % client.transport._host, args[1]) + + +def test_update_event_create_rule_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_event_create_rule( + analytics_admin.UpdateEventCreateRuleRequest(), + event_create_rule=event_create_and_edit.EventCreateRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_event_create_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteEventCreateRuleRequest, + dict, +]) +def test_delete_event_create_rule_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/eventCreateRules/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_event_create_rule(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_event_create_rule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_event_create_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_event_create_rule] = mock_rpc + + request = {} + client.delete_event_create_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_event_create_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_event_create_rule_rest_required_fields(request_type=analytics_admin.DeleteEventCreateRuleRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_event_create_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_event_create_rule._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 = AnalyticsAdminServiceClient( + 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_event_create_rule(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_event_create_rule_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_event_create_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_event_create_rule_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_event_create_rule") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteEventCreateRuleRequest.pb(analytics_admin.DeleteEventCreateRuleRequest()) + 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 = analytics_admin.DeleteEventCreateRuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_event_create_rule(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_event_create_rule_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteEventCreateRuleRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/eventCreateRules/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_event_create_rule(request) + + +def test_delete_event_create_rule_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/dataStreams/sample2/eventCreateRules/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_event_create_rule(**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/v1alpha/{name=properties/*/dataStreams/*/eventCreateRules/*}" % client.transport._host, args[1]) + + +def test_delete_event_create_rule_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_event_create_rule( + analytics_admin.DeleteEventCreateRuleRequest(), + name='name_value', + ) + + +def test_delete_event_create_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetEventEditRuleRequest, + dict, +]) +def test_get_event_edit_rule_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/eventEditRules/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 = event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = event_create_and_edit.EventEditRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_event_edit_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.processing_order == 1720 + +def test_get_event_edit_rule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_event_edit_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_event_edit_rule] = mock_rpc + + request = {} + client.get_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_event_edit_rule_rest_required_fields(request_type=analytics_admin.GetEventEditRuleRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_event_edit_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_event_edit_rule._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = event_create_and_edit.EventEditRule() + # 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 = event_create_and_edit.EventEditRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_event_edit_rule(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_event_edit_rule_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_event_edit_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_event_edit_rule_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_event_edit_rule") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_event_edit_rule") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetEventEditRuleRequest.pb(analytics_admin.GetEventEditRuleRequest()) + 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 = event_create_and_edit.EventEditRule.to_json(event_create_and_edit.EventEditRule()) + + request = analytics_admin.GetEventEditRuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = event_create_and_edit.EventEditRule() + + client.get_event_edit_rule(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_event_edit_rule_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetEventEditRuleRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/eventEditRules/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_event_edit_rule(request) + + +def test_get_event_edit_rule_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = event_create_and_edit.EventEditRule() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/sample2/eventEditRules/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 = event_create_and_edit.EventEditRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_event_edit_rule(**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/v1alpha/{name=properties/*/dataStreams/*/eventEditRules/*}" % client.transport._host, args[1]) + + +def test_get_event_edit_rule_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_event_edit_rule( + analytics_admin.GetEventEditRuleRequest(), + name='name_value', + ) + + +def test_get_event_edit_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListEventEditRulesRequest, + dict, +]) +def test_list_event_edit_rules_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListEventEditRulesResponse( + 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 = analytics_admin.ListEventEditRulesResponse.pb(return_value) + 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_event_edit_rules(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEventEditRulesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_event_edit_rules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_event_edit_rules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_event_edit_rules] = mock_rpc + + request = {} + client.list_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_event_edit_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_event_edit_rules_rest_required_fields(request_type=analytics_admin.ListEventEditRulesRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_event_edit_rules._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_event_edit_rules._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListEventEditRulesResponse() + # 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 = analytics_admin.ListEventEditRulesResponse.pb(return_value) + 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_event_edit_rules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_event_edit_rules_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_event_edit_rules._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_event_edit_rules_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_event_edit_rules") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_event_edit_rules") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListEventEditRulesRequest.pb(analytics_admin.ListEventEditRulesRequest()) + 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 = analytics_admin.ListEventEditRulesResponse.to_json(analytics_admin.ListEventEditRulesResponse()) + + request = analytics_admin.ListEventEditRulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListEventEditRulesResponse() + + client.list_event_edit_rules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_event_edit_rules_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListEventEditRulesRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_event_edit_rules(request) + + +def test_list_event_edit_rules_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListEventEditRulesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListEventEditRulesResponse.pb(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_event_edit_rules(**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/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules" % client.transport._host, args[1]) + + +def test_list_event_edit_rules_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_event_edit_rules( + analytics_admin.ListEventEditRulesRequest(), + parent='parent_value', + ) + + +def test_list_event_edit_rules_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + next_page_token='abc', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[], + next_page_token='def', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + ], + next_page_token='ghi', + ), + analytics_admin.ListEventEditRulesResponse( + event_edit_rules=[ + event_create_and_edit.EventEditRule(), + event_create_and_edit.EventEditRule(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListEventEditRulesResponse.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': 'properties/sample1/dataStreams/sample2'} + + pager = client.list_event_edit_rules(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, event_create_and_edit.EventEditRule) + for i in results) + + pages = list(client.list_event_edit_rules(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", [ + analytics_admin.CreateEventEditRuleRequest, + dict, +]) +def test_create_event_edit_rule_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/sample2'} + request_init["event_edit_rule"] = {'name': 'name_value', 'display_name': 'display_name_value', 'event_conditions': [{'field': 'field_value', 'comparison_type': 1, 'value': 'value_value', 'negated': True}], 'parameter_mutations': [{'parameter': 'parameter_value', 'parameter_value': 'parameter_value_value'}], 'processing_order': 1720} + # 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 = analytics_admin.CreateEventEditRuleRequest.meta.fields["event_edit_rule"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event_edit_rule"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event_edit_rule"][field])): + del request_init["event_edit_rule"][field][i][subfield] + else: + del request_init["event_edit_rule"][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 = event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = event_create_and_edit.EventEditRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_event_edit_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.processing_order == 1720 + +def test_create_event_edit_rule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_event_edit_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_event_edit_rule] = mock_rpc + + request = {} + client.create_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_event_edit_rule_rest_required_fields(request_type=analytics_admin.CreateEventEditRuleRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_event_edit_rule._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_event_edit_rule._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = event_create_and_edit.EventEditRule() + # 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 = event_create_and_edit.EventEditRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_event_edit_rule(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_event_edit_rule_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_event_edit_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "eventEditRule", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_event_edit_rule_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_event_edit_rule") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_event_edit_rule") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateEventEditRuleRequest.pb(analytics_admin.CreateEventEditRuleRequest()) + 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 = event_create_and_edit.EventEditRule.to_json(event_create_and_edit.EventEditRule()) + + request = analytics_admin.CreateEventEditRuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = event_create_and_edit.EventEditRule() + + client.create_event_edit_rule(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_event_edit_rule_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateEventEditRuleRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_event_edit_rule(request) + + +def test_create_event_edit_rule_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = event_create_and_edit.EventEditRule() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + event_edit_rule=event_create_and_edit.EventEditRule(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 = event_create_and_edit.EventEditRule.pb(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_event_edit_rule(**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/v1alpha/{parent=properties/*/dataStreams/*}/eventEditRules" % client.transport._host, args[1]) + + +def test_create_event_edit_rule_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_event_edit_rule( + analytics_admin.CreateEventEditRuleRequest(), + parent='parent_value', + event_edit_rule=event_create_and_edit.EventEditRule(name='name_value'), + ) + + +def test_create_event_edit_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateEventEditRuleRequest, + dict, +]) +def test_update_event_edit_rule_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'event_edit_rule': {'name': 'properties/sample1/dataStreams/sample2/eventEditRules/sample3'}} + request_init["event_edit_rule"] = {'name': 'properties/sample1/dataStreams/sample2/eventEditRules/sample3', 'display_name': 'display_name_value', 'event_conditions': [{'field': 'field_value', 'comparison_type': 1, 'value': 'value_value', 'negated': True}], 'parameter_mutations': [{'parameter': 'parameter_value', 'parameter_value': 'parameter_value_value'}], 'processing_order': 1720} + # 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 = analytics_admin.UpdateEventEditRuleRequest.meta.fields["event_edit_rule"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["event_edit_rule"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["event_edit_rule"][field])): + del request_init["event_edit_rule"][field][i][subfield] + else: + del request_init["event_edit_rule"][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 = event_create_and_edit.EventEditRule( + name='name_value', + display_name='display_name_value', + processing_order=1720, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = event_create_and_edit.EventEditRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_event_edit_rule(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, event_create_and_edit.EventEditRule) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.processing_order == 1720 + +def test_update_event_edit_rule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_event_edit_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_event_edit_rule] = mock_rpc + + request = {} + client.update_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_event_edit_rule_rest_required_fields(request_type=analytics_admin.UpdateEventEditRuleRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_event_edit_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_event_edit_rule._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = event_create_and_edit.EventEditRule() + # 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 = event_create_and_edit.EventEditRule.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_event_edit_rule(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_event_edit_rule_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_event_edit_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("eventEditRule", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_event_edit_rule_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_event_edit_rule") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_event_edit_rule") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateEventEditRuleRequest.pb(analytics_admin.UpdateEventEditRuleRequest()) + 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 = event_create_and_edit.EventEditRule.to_json(event_create_and_edit.EventEditRule()) + + request = analytics_admin.UpdateEventEditRuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = event_create_and_edit.EventEditRule() + + client.update_event_edit_rule(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_event_edit_rule_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateEventEditRuleRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'event_edit_rule': {'name': 'properties/sample1/dataStreams/sample2/eventEditRules/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_event_edit_rule(request) + + +def test_update_event_edit_rule_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = event_create_and_edit.EventEditRule() + + # get arguments that satisfy an http rule for this method + sample_request = {'event_edit_rule': {'name': 'properties/sample1/dataStreams/sample2/eventEditRules/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + event_edit_rule=event_create_and_edit.EventEditRule(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 = event_create_and_edit.EventEditRule.pb(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_event_edit_rule(**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/v1alpha/{event_edit_rule.name=properties/*/dataStreams/*/eventEditRules/*}" % client.transport._host, args[1]) + + +def test_update_event_edit_rule_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_event_edit_rule( + analytics_admin.UpdateEventEditRuleRequest(), + event_edit_rule=event_create_and_edit.EventEditRule(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_event_edit_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteEventEditRuleRequest, + dict, +]) +def test_delete_event_edit_rule_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/eventEditRules/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_event_edit_rule(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_event_edit_rule_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_event_edit_rule in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_event_edit_rule] = mock_rpc + + request = {} + client.delete_event_edit_rule(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_event_edit_rule(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_event_edit_rule_rest_required_fields(request_type=analytics_admin.DeleteEventEditRuleRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_event_edit_rule._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_event_edit_rule._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 = AnalyticsAdminServiceClient( + 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_event_edit_rule(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_event_edit_rule_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_event_edit_rule._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_event_edit_rule_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_event_edit_rule") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteEventEditRuleRequest.pb(analytics_admin.DeleteEventEditRuleRequest()) + 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 = analytics_admin.DeleteEventEditRuleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_event_edit_rule(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_event_edit_rule_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteEventEditRuleRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/eventEditRules/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_event_edit_rule(request) + + +def test_delete_event_edit_rule_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/dataStreams/sample2/eventEditRules/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_event_edit_rule(**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/v1alpha/{name=properties/*/dataStreams/*/eventEditRules/*}" % client.transport._host, args[1]) + + +def test_delete_event_edit_rule_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_event_edit_rule( + analytics_admin.DeleteEventEditRuleRequest(), + name='name_value', + ) + + +def test_delete_event_edit_rule_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ReorderEventEditRulesRequest, + dict, +]) +def test_reorder_event_edit_rules_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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.reorder_event_edit_rules(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_reorder_event_edit_rules_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.reorder_event_edit_rules in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.reorder_event_edit_rules] = mock_rpc + + request = {} + client.reorder_event_edit_rules(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.reorder_event_edit_rules(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_reorder_event_edit_rules_rest_required_fields(request_type=analytics_admin.ReorderEventEditRulesRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["event_edit_rules"] = "" + 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()).reorder_event_edit_rules._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["eventEditRules"] = 'event_edit_rules_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).reorder_event_edit_rules._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 "eventEditRules" in jsonified_request + assert jsonified_request["eventEditRules"] == 'event_edit_rules_value' + + client = AnalyticsAdminServiceClient( + 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': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.reorder_event_edit_rules(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_reorder_event_edit_rules_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.reorder_event_edit_rules._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "eventEditRules", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reorder_event_edit_rules_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_reorder_event_edit_rules") as pre: + pre.assert_not_called() + pb_message = analytics_admin.ReorderEventEditRulesRequest.pb(analytics_admin.ReorderEventEditRulesRequest()) + 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 = analytics_admin.ReorderEventEditRulesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.reorder_event_edit_rules(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_reorder_event_edit_rules_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ReorderEventEditRulesRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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.reorder_event_edit_rules(request) + + +def test_reorder_event_edit_rules_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDataRedactionSettingsRequest, + dict, +]) +def test_update_data_redaction_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_redaction_settings': {'name': 'properties/sample1/dataStreams/sample2/dataRedactionSettings'}} + request_init["data_redaction_settings"] = {'name': 'properties/sample1/dataStreams/sample2/dataRedactionSettings', 'email_redaction_enabled': True, 'query_parameter_redaction_enabled': True, 'query_parameter_keys': ['query_parameter_keys_value1', 'query_parameter_keys_value2']} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateDataRedactionSettingsRequest.meta.fields["data_redaction_settings"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_redaction_settings"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_redaction_settings"][field])): + del request_init["data_redaction_settings"][field][i][subfield] + else: + del request_init["data_redaction_settings"][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 = resources.DataRedactionSettings( + name='name_value', + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=['query_parameter_keys_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 = resources.DataRedactionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_data_redaction_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRedactionSettings) + assert response.name == 'name_value' + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ['query_parameter_keys_value'] + +def test_update_data_redaction_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_redaction_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_redaction_settings] = mock_rpc + + request = {} + client.update_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_redaction_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_data_redaction_settings_rest_required_fields(request_type=analytics_admin.UpdateDataRedactionSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_redaction_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_redaction_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataRedactionSettings() + # 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 = resources.DataRedactionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_data_redaction_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_data_redaction_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_data_redaction_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("dataRedactionSettings", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_redaction_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_data_redaction_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_data_redaction_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateDataRedactionSettingsRequest.pb(analytics_admin.UpdateDataRedactionSettingsRequest()) + 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 = resources.DataRedactionSettings.to_json(resources.DataRedactionSettings()) + + request = analytics_admin.UpdateDataRedactionSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataRedactionSettings() + + client.update_data_redaction_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_data_redaction_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateDataRedactionSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_redaction_settings': {'name': 'properties/sample1/dataStreams/sample2/dataRedactionSettings'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_data_redaction_settings(request) + + +def test_update_data_redaction_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataRedactionSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'data_redaction_settings': {'name': 'properties/sample1/dataStreams/sample2/dataRedactionSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + data_redaction_settings=resources.DataRedactionSettings(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 = resources.DataRedactionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_data_redaction_settings(**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/v1alpha/{data_redaction_settings.name=properties/*/dataStreams/*/dataRedactionSettings}" % client.transport._host, args[1]) + + +def test_update_data_redaction_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_redaction_settings( + analytics_admin.UpdateDataRedactionSettingsRequest(), + data_redaction_settings=resources.DataRedactionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_data_redaction_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataRedactionSettingsRequest, + dict, +]) +def test_get_data_redaction_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/dataRedactionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataRedactionSettings( + name='name_value', + email_redaction_enabled=True, + query_parameter_redaction_enabled=True, + query_parameter_keys=['query_parameter_keys_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 = resources.DataRedactionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_redaction_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRedactionSettings) + assert response.name == 'name_value' + assert response.email_redaction_enabled is True + assert response.query_parameter_redaction_enabled is True + assert response.query_parameter_keys == ['query_parameter_keys_value'] + +def test_get_data_redaction_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_redaction_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_redaction_settings] = mock_rpc + + request = {} + client.get_data_redaction_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_redaction_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_redaction_settings_rest_required_fields(request_type=analytics_admin.GetDataRedactionSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_redaction_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_redaction_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataRedactionSettings() + # 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 = resources.DataRedactionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_redaction_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_redaction_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_redaction_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_redaction_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_data_redaction_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_redaction_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetDataRedactionSettingsRequest.pb(analytics_admin.GetDataRedactionSettingsRequest()) + 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 = resources.DataRedactionSettings.to_json(resources.DataRedactionSettings()) + + request = analytics_admin.GetDataRedactionSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataRedactionSettings() + + client.get_data_redaction_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_redaction_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetDataRedactionSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/dataRedactionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_data_redaction_settings(request) + + +def test_get_data_redaction_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataRedactionSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/sample2/dataRedactionSettings'} + + # 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 = resources.DataRedactionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_redaction_settings(**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/v1alpha/{name=properties/*/dataStreams/*/dataRedactionSettings}" % client.transport._host, args[1]) + + +def test_get_data_redaction_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_redaction_settings( + analytics_admin.GetDataRedactionSettingsRequest(), + name='name_value', + ) + + +def test_get_data_redaction_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCalculatedMetricRequest, + dict, +]) +def test_get_calculated_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/calculatedMetrics/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 = resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=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 = resources.CalculatedMetric.pb(return_value) + 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_calculated_metric(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.display_name == 'display_name_value' + assert response.calculated_metric_id == 'calculated_metric_id_value' + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [resources.CalculatedMetric.RestrictedMetricType.COST_DATA] + assert response.formula == 'formula_value' + assert response.invalid_metric_reference is True + +def test_get_calculated_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_calculated_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_calculated_metric] = mock_rpc + + request = {} + client.get_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_calculated_metric_rest_required_fields(request_type=analytics_admin.GetCalculatedMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_calculated_metric._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_calculated_metric._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CalculatedMetric() + # 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 = resources.CalculatedMetric.pb(return_value) + 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_calculated_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_calculated_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_calculated_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_calculated_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_calculated_metric") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_calculated_metric") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetCalculatedMetricRequest.pb(analytics_admin.GetCalculatedMetricRequest()) + 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 = resources.CalculatedMetric.to_json(resources.CalculatedMetric()) + + request = analytics_admin.GetCalculatedMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CalculatedMetric() + + client.get_calculated_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_calculated_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetCalculatedMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/calculatedMetrics/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_calculated_metric(request) + + +def test_get_calculated_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CalculatedMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/calculatedMetrics/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 = resources.CalculatedMetric.pb(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_calculated_metric(**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/v1alpha/{name=properties/*/calculatedMetrics/*}" % client.transport._host, args[1]) + + +def test_get_calculated_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_calculated_metric( + analytics_admin.GetCalculatedMetricRequest(), + name='name_value', + ) + + +def test_get_calculated_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateCalculatedMetricRequest, + dict, +]) +def test_create_calculated_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["calculated_metric"] = {'name': 'name_value', 'description': 'description_value', 'display_name': 'display_name_value', 'calculated_metric_id': 'calculated_metric_id_value', 'metric_unit': 1, 'restricted_metric_type': [1], 'formula': 'formula_value', 'invalid_metric_reference': 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 = analytics_admin.CreateCalculatedMetricRequest.meta.fields["calculated_metric"] + + 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["calculated_metric"].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["calculated_metric"][field])): + del request_init["calculated_metric"][field][i][subfield] + else: + del request_init["calculated_metric"][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 = resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=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 = resources.CalculatedMetric.pb(return_value) + 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_calculated_metric(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.display_name == 'display_name_value' + assert response.calculated_metric_id == 'calculated_metric_id_value' + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [resources.CalculatedMetric.RestrictedMetricType.COST_DATA] + assert response.formula == 'formula_value' + assert response.invalid_metric_reference is True + +def test_create_calculated_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_calculated_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_calculated_metric] = mock_rpc + + request = {} + client.create_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_calculated_metric_rest_required_fields(request_type=analytics_admin.CreateCalculatedMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["calculated_metric_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "calculatedMetricId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_calculated_metric._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "calculatedMetricId" in jsonified_request + assert jsonified_request["calculatedMetricId"] == request_init["calculated_metric_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["calculatedMetricId"] = 'calculated_metric_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_calculated_metric._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("calculated_metric_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "calculatedMetricId" in jsonified_request + assert jsonified_request["calculatedMetricId"] == 'calculated_metric_id_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CalculatedMetric() + # 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 = resources.CalculatedMetric.pb(return_value) + 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_calculated_metric(request) + + expected_params = [ + ( + "calculatedMetricId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_calculated_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_calculated_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(("calculatedMetricId", )) & set(("parent", "calculatedMetricId", "calculatedMetric", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_calculated_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_calculated_metric") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_calculated_metric") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateCalculatedMetricRequest.pb(analytics_admin.CreateCalculatedMetricRequest()) + 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 = resources.CalculatedMetric.to_json(resources.CalculatedMetric()) + + request = analytics_admin.CreateCalculatedMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CalculatedMetric() + + client.create_calculated_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_calculated_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateCalculatedMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_calculated_metric(request) + + +def test_create_calculated_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CalculatedMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + calculated_metric=resources.CalculatedMetric(name='name_value'), + calculated_metric_id='calculated_metric_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 = resources.CalculatedMetric.pb(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_calculated_metric(**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/v1alpha/{parent=properties/*}/calculatedMetrics" % client.transport._host, args[1]) + + +def test_create_calculated_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_calculated_metric( + analytics_admin.CreateCalculatedMetricRequest(), + parent='parent_value', + calculated_metric=resources.CalculatedMetric(name='name_value'), + calculated_metric_id='calculated_metric_id_value', + ) + + +def test_create_calculated_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCalculatedMetricsRequest, + dict, +]) +def test_list_calculated_metrics_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListCalculatedMetricsResponse( + 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 = analytics_admin.ListCalculatedMetricsResponse.pb(return_value) + 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_calculated_metrics(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCalculatedMetricsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_calculated_metrics_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_calculated_metrics in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_calculated_metrics] = mock_rpc + + request = {} + client.list_calculated_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_calculated_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_calculated_metrics_rest_required_fields(request_type=analytics_admin.ListCalculatedMetricsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_calculated_metrics._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_calculated_metrics._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListCalculatedMetricsResponse() + # 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 = analytics_admin.ListCalculatedMetricsResponse.pb(return_value) + 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_calculated_metrics(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_calculated_metrics_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_calculated_metrics._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_calculated_metrics_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_calculated_metrics") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_calculated_metrics") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListCalculatedMetricsRequest.pb(analytics_admin.ListCalculatedMetricsRequest()) + 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 = analytics_admin.ListCalculatedMetricsResponse.to_json(analytics_admin.ListCalculatedMetricsResponse()) + + request = analytics_admin.ListCalculatedMetricsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListCalculatedMetricsResponse() + + client.list_calculated_metrics(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_calculated_metrics_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListCalculatedMetricsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_calculated_metrics(request) + + +def test_list_calculated_metrics_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCalculatedMetricsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListCalculatedMetricsResponse.pb(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_calculated_metrics(**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/v1alpha/{parent=properties/*}/calculatedMetrics" % client.transport._host, args[1]) + + +def test_list_calculated_metrics_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_calculated_metrics( + analytics_admin.ListCalculatedMetricsRequest(), + parent='parent_value', + ) + + +def test_list_calculated_metrics_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCalculatedMetricsResponse( + calculated_metrics=[ + resources.CalculatedMetric(), + resources.CalculatedMetric(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListCalculatedMetricsResponse.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': 'properties/sample1'} + + pager = client.list_calculated_metrics(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CalculatedMetric) + for i in results) + + pages = list(client.list_calculated_metrics(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", [ + analytics_admin.UpdateCalculatedMetricRequest, + dict, +]) +def test_update_calculated_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'calculated_metric': {'name': 'properties/sample1/calculatedMetrics/sample2'}} + request_init["calculated_metric"] = {'name': 'properties/sample1/calculatedMetrics/sample2', 'description': 'description_value', 'display_name': 'display_name_value', 'calculated_metric_id': 'calculated_metric_id_value', 'metric_unit': 1, 'restricted_metric_type': [1], 'formula': 'formula_value', 'invalid_metric_reference': 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 = analytics_admin.UpdateCalculatedMetricRequest.meta.fields["calculated_metric"] + + 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["calculated_metric"].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["calculated_metric"][field])): + del request_init["calculated_metric"][field][i][subfield] + else: + del request_init["calculated_metric"][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 = resources.CalculatedMetric( + name='name_value', + description='description_value', + display_name='display_name_value', + calculated_metric_id='calculated_metric_id_value', + metric_unit=resources.CalculatedMetric.MetricUnit.STANDARD, + restricted_metric_type=[resources.CalculatedMetric.RestrictedMetricType.COST_DATA], + formula='formula_value', + invalid_metric_reference=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 = resources.CalculatedMetric.pb(return_value) + 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_calculated_metric(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CalculatedMetric) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.display_name == 'display_name_value' + assert response.calculated_metric_id == 'calculated_metric_id_value' + assert response.metric_unit == resources.CalculatedMetric.MetricUnit.STANDARD + assert response.restricted_metric_type == [resources.CalculatedMetric.RestrictedMetricType.COST_DATA] + assert response.formula == 'formula_value' + assert response.invalid_metric_reference is True + +def test_update_calculated_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_calculated_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_calculated_metric] = mock_rpc + + request = {} + client.update_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_calculated_metric_rest_required_fields(request_type=analytics_admin.UpdateCalculatedMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_calculated_metric._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_calculated_metric._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CalculatedMetric() + # 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 = resources.CalculatedMetric.pb(return_value) + 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_calculated_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_calculated_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_calculated_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("calculatedMetric", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_calculated_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_calculated_metric") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_calculated_metric") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateCalculatedMetricRequest.pb(analytics_admin.UpdateCalculatedMetricRequest()) + 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 = resources.CalculatedMetric.to_json(resources.CalculatedMetric()) + + request = analytics_admin.UpdateCalculatedMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CalculatedMetric() + + client.update_calculated_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_calculated_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateCalculatedMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'calculated_metric': {'name': 'properties/sample1/calculatedMetrics/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_calculated_metric(request) + + +def test_update_calculated_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CalculatedMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {'calculated_metric': {'name': 'properties/sample1/calculatedMetrics/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + calculated_metric=resources.CalculatedMetric(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 = resources.CalculatedMetric.pb(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_calculated_metric(**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/v1alpha/{calculated_metric.name=properties/*/calculatedMetrics/*}" % client.transport._host, args[1]) + + +def test_update_calculated_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_calculated_metric( + analytics_admin.UpdateCalculatedMetricRequest(), + calculated_metric=resources.CalculatedMetric(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_calculated_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteCalculatedMetricRequest, + dict, +]) +def test_delete_calculated_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/calculatedMetrics/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_calculated_metric(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_calculated_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_calculated_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_calculated_metric] = mock_rpc + + request = {} + client.delete_calculated_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_calculated_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_calculated_metric_rest_required_fields(request_type=analytics_admin.DeleteCalculatedMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_calculated_metric._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_calculated_metric._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 = AnalyticsAdminServiceClient( + 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_calculated_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_calculated_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_calculated_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_calculated_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_calculated_metric") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteCalculatedMetricRequest.pb(analytics_admin.DeleteCalculatedMetricRequest()) + 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 = analytics_admin.DeleteCalculatedMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_calculated_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_calculated_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteCalculatedMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/calculatedMetrics/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_calculated_metric(request) + + +def test_delete_calculated_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/calculatedMetrics/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_calculated_metric(**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/v1alpha/{name=properties/*/calculatedMetrics/*}" % client.transport._host, args[1]) + + +def test_delete_calculated_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_calculated_metric( + analytics_admin.DeleteCalculatedMetricRequest(), + name='name_value', + ) + + +def test_delete_calculated_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateRollupPropertyRequest, + dict, +]) +def test_create_rollup_property_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateRollupPropertyResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.CreateRollupPropertyResponse.pb(return_value) + 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_rollup_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.CreateRollupPropertyResponse) + +def test_create_rollup_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_rollup_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_rollup_property] = mock_rpc + + request = {} + client.create_rollup_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_rollup_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_rollup_property_rest_required_fields(request_type=analytics_admin.CreateRollupPropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_rollup_property._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_rollup_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.CreateRollupPropertyResponse() + # 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 = analytics_admin.CreateRollupPropertyResponse.pb(return_value) + 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_rollup_property(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_rollup_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_rollup_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("rollupProperty", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_rollup_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_rollup_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_rollup_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateRollupPropertyRequest.pb(analytics_admin.CreateRollupPropertyRequest()) + 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 = analytics_admin.CreateRollupPropertyResponse.to_json(analytics_admin.CreateRollupPropertyResponse()) + + request = analytics_admin.CreateRollupPropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.CreateRollupPropertyResponse() + + client.create_rollup_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_rollup_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateRollupPropertyRequest): + client = AnalyticsAdminServiceClient( + 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_rollup_property(request) + + +def test_create_rollup_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetRollupPropertySourceLinkRequest, + dict, +]) +def test_get_rollup_property_source_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/rollupPropertySourceLinks/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 = resources.RollupPropertySourceLink( + name='name_value', + source_property='source_property_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 = resources.RollupPropertySourceLink.pb(return_value) + 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_rollup_property_source_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == 'name_value' + assert response.source_property == 'source_property_value' + +def test_get_rollup_property_source_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_rollup_property_source_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_rollup_property_source_link] = mock_rpc + + request = {} + client.get_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_rollup_property_source_link_rest_required_fields(request_type=analytics_admin.GetRollupPropertySourceLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_rollup_property_source_link._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_rollup_property_source_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.RollupPropertySourceLink() + # 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 = resources.RollupPropertySourceLink.pb(return_value) + 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_rollup_property_source_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_rollup_property_source_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_rollup_property_source_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rollup_property_source_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_rollup_property_source_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_rollup_property_source_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetRollupPropertySourceLinkRequest.pb(analytics_admin.GetRollupPropertySourceLinkRequest()) + 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 = resources.RollupPropertySourceLink.to_json(resources.RollupPropertySourceLink()) + + request = analytics_admin.GetRollupPropertySourceLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.RollupPropertySourceLink() + + client.get_rollup_property_source_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_rollup_property_source_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetRollupPropertySourceLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/rollupPropertySourceLinks/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_rollup_property_source_link(request) + + +def test_get_rollup_property_source_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.RollupPropertySourceLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/rollupPropertySourceLinks/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 = resources.RollupPropertySourceLink.pb(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_rollup_property_source_link(**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/v1alpha/{name=properties/*/rollupPropertySourceLinks/*}" % client.transport._host, args[1]) + + +def test_get_rollup_property_source_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_rollup_property_source_link( + analytics_admin.GetRollupPropertySourceLinkRequest(), + name='name_value', + ) + + +def test_get_rollup_property_source_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListRollupPropertySourceLinksRequest, + dict, +]) +def test_list_rollup_property_source_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListRollupPropertySourceLinksResponse( + 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 = analytics_admin.ListRollupPropertySourceLinksResponse.pb(return_value) + 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_rollup_property_source_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRollupPropertySourceLinksPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_rollup_property_source_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_rollup_property_source_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_rollup_property_source_links] = mock_rpc + + request = {} + client.list_rollup_property_source_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_rollup_property_source_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_rollup_property_source_links_rest_required_fields(request_type=analytics_admin.ListRollupPropertySourceLinksRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_rollup_property_source_links._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_rollup_property_source_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + # 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 = analytics_admin.ListRollupPropertySourceLinksResponse.pb(return_value) + 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_rollup_property_source_links(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_rollup_property_source_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_rollup_property_source_links._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rollup_property_source_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_rollup_property_source_links") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_rollup_property_source_links") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListRollupPropertySourceLinksRequest.pb(analytics_admin.ListRollupPropertySourceLinksRequest()) + 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 = analytics_admin.ListRollupPropertySourceLinksResponse.to_json(analytics_admin.ListRollupPropertySourceLinksResponse()) + + request = analytics_admin.ListRollupPropertySourceLinksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListRollupPropertySourceLinksResponse() + + client.list_rollup_property_source_links(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_rollup_property_source_links_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListRollupPropertySourceLinksRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_rollup_property_source_links(request) + + +def test_list_rollup_property_source_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListRollupPropertySourceLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListRollupPropertySourceLinksResponse.pb(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_rollup_property_source_links(**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/v1alpha/{parent=properties/*}/rollupPropertySourceLinks" % client.transport._host, args[1]) + + +def test_list_rollup_property_source_links_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_rollup_property_source_links( + analytics_admin.ListRollupPropertySourceLinksRequest(), + parent='parent_value', + ) + + +def test_list_rollup_property_source_links_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[], + next_page_token='def', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListRollupPropertySourceLinksResponse( + rollup_property_source_links=[ + resources.RollupPropertySourceLink(), + resources.RollupPropertySourceLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListRollupPropertySourceLinksResponse.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': 'properties/sample1'} + + pager = client.list_rollup_property_source_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.RollupPropertySourceLink) + for i in results) + + pages = list(client.list_rollup_property_source_links(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", [ + analytics_admin.CreateRollupPropertySourceLinkRequest, + dict, +]) +def test_create_rollup_property_source_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["rollup_property_source_link"] = {'name': 'name_value', 'source_property': 'source_property_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 = analytics_admin.CreateRollupPropertySourceLinkRequest.meta.fields["rollup_property_source_link"] + + 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["rollup_property_source_link"].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["rollup_property_source_link"][field])): + del request_init["rollup_property_source_link"][field][i][subfield] + else: + del request_init["rollup_property_source_link"][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 = resources.RollupPropertySourceLink( + name='name_value', + source_property='source_property_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 = resources.RollupPropertySourceLink.pb(return_value) + 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_rollup_property_source_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.RollupPropertySourceLink) + assert response.name == 'name_value' + assert response.source_property == 'source_property_value' + +def test_create_rollup_property_source_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_rollup_property_source_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_rollup_property_source_link] = mock_rpc + + request = {} + client.create_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_rollup_property_source_link_rest_required_fields(request_type=analytics_admin.CreateRollupPropertySourceLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_rollup_property_source_link._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_rollup_property_source_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.RollupPropertySourceLink() + # 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 = resources.RollupPropertySourceLink.pb(return_value) + 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_rollup_property_source_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_rollup_property_source_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_rollup_property_source_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "rollupPropertySourceLink", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_rollup_property_source_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_rollup_property_source_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_rollup_property_source_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateRollupPropertySourceLinkRequest.pb(analytics_admin.CreateRollupPropertySourceLinkRequest()) + 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 = resources.RollupPropertySourceLink.to_json(resources.RollupPropertySourceLink()) + + request = analytics_admin.CreateRollupPropertySourceLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.RollupPropertySourceLink() + + client.create_rollup_property_source_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_rollup_property_source_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateRollupPropertySourceLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_rollup_property_source_link(request) + + +def test_create_rollup_property_source_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.RollupPropertySourceLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + rollup_property_source_link=resources.RollupPropertySourceLink(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 = resources.RollupPropertySourceLink.pb(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_rollup_property_source_link(**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/v1alpha/{parent=properties/*}/rollupPropertySourceLinks" % client.transport._host, args[1]) + + +def test_create_rollup_property_source_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_rollup_property_source_link( + analytics_admin.CreateRollupPropertySourceLinkRequest(), + parent='parent_value', + rollup_property_source_link=resources.RollupPropertySourceLink(name='name_value'), + ) + + +def test_create_rollup_property_source_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteRollupPropertySourceLinkRequest, + dict, +]) +def test_delete_rollup_property_source_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/rollupPropertySourceLinks/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_rollup_property_source_link(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_rollup_property_source_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_rollup_property_source_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_rollup_property_source_link] = mock_rpc + + request = {} + client.delete_rollup_property_source_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_rollup_property_source_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_rollup_property_source_link_rest_required_fields(request_type=analytics_admin.DeleteRollupPropertySourceLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_rollup_property_source_link._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_rollup_property_source_link._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 = AnalyticsAdminServiceClient( + 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_rollup_property_source_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_rollup_property_source_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_rollup_property_source_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rollup_property_source_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_rollup_property_source_link") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteRollupPropertySourceLinkRequest.pb(analytics_admin.DeleteRollupPropertySourceLinkRequest()) + 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 = analytics_admin.DeleteRollupPropertySourceLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_rollup_property_source_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_rollup_property_source_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteRollupPropertySourceLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/rollupPropertySourceLinks/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_rollup_property_source_link(request) + + +def test_delete_rollup_property_source_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/rollupPropertySourceLinks/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_rollup_property_source_link(**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/v1alpha/{name=properties/*/rollupPropertySourceLinks/*}" % client.transport._host, args[1]) + + +def test_delete_rollup_property_source_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_rollup_property_source_link( + analytics_admin.DeleteRollupPropertySourceLinkRequest(), + name='name_value', + ) + + +def test_delete_rollup_property_source_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ProvisionSubpropertyRequest, + dict, +]) +def test_provision_subproperty_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ProvisionSubpropertyResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.ProvisionSubpropertyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.provision_subproperty(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionSubpropertyResponse) + +def test_provision_subproperty_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.provision_subproperty in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.provision_subproperty] = mock_rpc + + request = {} + client.provision_subproperty(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provision_subproperty(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_provision_subproperty_rest_required_fields(request_type=analytics_admin.ProvisionSubpropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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()).provision_subproperty._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()).provision_subproperty._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ProvisionSubpropertyResponse() + # 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 = analytics_admin.ProvisionSubpropertyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.provision_subproperty(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_provision_subproperty_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.provision_subproperty._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("subproperty", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_provision_subproperty_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_provision_subproperty") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_provision_subproperty") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ProvisionSubpropertyRequest.pb(analytics_admin.ProvisionSubpropertyRequest()) + 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 = analytics_admin.ProvisionSubpropertyResponse.to_json(analytics_admin.ProvisionSubpropertyResponse()) + + request = analytics_admin.ProvisionSubpropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ProvisionSubpropertyResponse() + + client.provision_subproperty(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_provision_subproperty_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ProvisionSubpropertyRequest): + client = AnalyticsAdminServiceClient( + 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.provision_subproperty(request) + + +def test_provision_subproperty_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateSubpropertyEventFilterRequest, + dict, +]) +def test_create_subproperty_event_filter_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["subproperty_event_filter"] = {'name': 'name_value', 'apply_to_property': 'apply_to_property_value', 'filter_clauses': [{'filter_clause_type': 1, 'filter_expression': {'or_group': {'filter_expressions': {}}, 'not_expression': {}, 'filter_condition': {'null_filter': True, 'string_filter': {'match_type': 1, 'value': 'value_value', 'case_sensitive': True}, 'field_name': 'field_name_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 = analytics_admin.CreateSubpropertyEventFilterRequest.meta.fields["subproperty_event_filter"] + + 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["subproperty_event_filter"].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["subproperty_event_filter"][field])): + del request_init["subproperty_event_filter"][field][i][subfield] + else: + del request_init["subproperty_event_filter"][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 = gaa_subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_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 = gaa_subproperty_event_filter.SubpropertyEventFilter.pb(return_value) + 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_subproperty_event_filter(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == 'name_value' + assert response.apply_to_property == 'apply_to_property_value' + +def test_create_subproperty_event_filter_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_subproperty_event_filter in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_subproperty_event_filter] = mock_rpc + + request = {} + client.create_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_subproperty_event_filter_rest_required_fields(request_type=analytics_admin.CreateSubpropertyEventFilterRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_subproperty_event_filter._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_subproperty_event_filter._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + # 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 = gaa_subproperty_event_filter.SubpropertyEventFilter.pb(return_value) + 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_subproperty_event_filter(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_subproperty_event_filter_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_subproperty_event_filter._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "subpropertyEventFilter", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_subproperty_event_filter_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_subproperty_event_filter") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_subproperty_event_filter") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateSubpropertyEventFilterRequest.pb(analytics_admin.CreateSubpropertyEventFilterRequest()) + 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 = gaa_subproperty_event_filter.SubpropertyEventFilter.to_json(gaa_subproperty_event_filter.SubpropertyEventFilter()) + + request = analytics_admin.CreateSubpropertyEventFilterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + + client.create_subproperty_event_filter(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_subproperty_event_filter_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateSubpropertyEventFilterRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_subproperty_event_filter(request) + + +def test_create_subproperty_event_filter_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = gaa_subproperty_event_filter.SubpropertyEventFilter() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(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 = gaa_subproperty_event_filter.SubpropertyEventFilter.pb(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_subproperty_event_filter(**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/v1alpha/{parent=properties/*}/subpropertyEventFilters" % client.transport._host, args[1]) + + +def test_create_subproperty_event_filter_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_subproperty_event_filter( + analytics_admin.CreateSubpropertyEventFilterRequest(), + parent='parent_value', + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(name='name_value'), + ) + + +def test_create_subproperty_event_filter_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetSubpropertyEventFilterRequest, + dict, +]) +def test_get_subproperty_event_filter_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/subpropertyEventFilters/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 = subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_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 = subproperty_event_filter.SubpropertyEventFilter.pb(return_value) + 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_subproperty_event_filter(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, subproperty_event_filter.SubpropertyEventFilter) + assert response.name == 'name_value' + assert response.apply_to_property == 'apply_to_property_value' + +def test_get_subproperty_event_filter_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_subproperty_event_filter in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_subproperty_event_filter] = mock_rpc + + request = {} + client.get_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_subproperty_event_filter_rest_required_fields(request_type=analytics_admin.GetSubpropertyEventFilterRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_subproperty_event_filter._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_subproperty_event_filter._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = subproperty_event_filter.SubpropertyEventFilter() + # 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 = subproperty_event_filter.SubpropertyEventFilter.pb(return_value) + 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_subproperty_event_filter(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_subproperty_event_filter_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_subproperty_event_filter._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_subproperty_event_filter_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_subproperty_event_filter") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_subproperty_event_filter") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetSubpropertyEventFilterRequest.pb(analytics_admin.GetSubpropertyEventFilterRequest()) + 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 = subproperty_event_filter.SubpropertyEventFilter.to_json(subproperty_event_filter.SubpropertyEventFilter()) + + request = analytics_admin.GetSubpropertyEventFilterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = subproperty_event_filter.SubpropertyEventFilter() + + client.get_subproperty_event_filter(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_subproperty_event_filter_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetSubpropertyEventFilterRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/subpropertyEventFilters/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_subproperty_event_filter(request) + + +def test_get_subproperty_event_filter_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = subproperty_event_filter.SubpropertyEventFilter() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/subpropertyEventFilters/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 = subproperty_event_filter.SubpropertyEventFilter.pb(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_subproperty_event_filter(**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/v1alpha/{name=properties/*/subpropertyEventFilters/*}" % client.transport._host, args[1]) + + +def test_get_subproperty_event_filter_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_subproperty_event_filter( + analytics_admin.GetSubpropertyEventFilterRequest(), + name='name_value', + ) + + +def test_get_subproperty_event_filter_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListSubpropertyEventFiltersRequest, + dict, +]) +def test_list_subproperty_event_filters_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListSubpropertyEventFiltersResponse( + 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 = analytics_admin.ListSubpropertyEventFiltersResponse.pb(return_value) + 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_subproperty_event_filters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSubpropertyEventFiltersPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_subproperty_event_filters_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_subproperty_event_filters in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_subproperty_event_filters] = mock_rpc + + request = {} + client.list_subproperty_event_filters(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_subproperty_event_filters(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_subproperty_event_filters_rest_required_fields(request_type=analytics_admin.ListSubpropertyEventFiltersRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_subproperty_event_filters._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_subproperty_event_filters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListSubpropertyEventFiltersResponse() + # 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 = analytics_admin.ListSubpropertyEventFiltersResponse.pb(return_value) + 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_subproperty_event_filters(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_subproperty_event_filters_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_subproperty_event_filters._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_subproperty_event_filters_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_subproperty_event_filters") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_subproperty_event_filters") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListSubpropertyEventFiltersRequest.pb(analytics_admin.ListSubpropertyEventFiltersRequest()) + 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 = analytics_admin.ListSubpropertyEventFiltersResponse.to_json(analytics_admin.ListSubpropertyEventFiltersResponse()) + + request = analytics_admin.ListSubpropertyEventFiltersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListSubpropertyEventFiltersResponse() + + client.list_subproperty_event_filters(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_subproperty_event_filters_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListSubpropertyEventFiltersRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_subproperty_event_filters(request) + + +def test_list_subproperty_event_filters_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListSubpropertyEventFiltersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListSubpropertyEventFiltersResponse.pb(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_subproperty_event_filters(**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/v1alpha/{parent=properties/*}/subpropertyEventFilters" % client.transport._host, args[1]) + + +def test_list_subproperty_event_filters_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_subproperty_event_filters( + analytics_admin.ListSubpropertyEventFiltersRequest(), + parent='parent_value', + ) + + +def test_list_subproperty_event_filters_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='abc', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[], + next_page_token='def', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + ], + next_page_token='ghi', + ), + analytics_admin.ListSubpropertyEventFiltersResponse( + subproperty_event_filters=[ + subproperty_event_filter.SubpropertyEventFilter(), + subproperty_event_filter.SubpropertyEventFilter(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListSubpropertyEventFiltersResponse.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': 'properties/sample1'} + + pager = client.list_subproperty_event_filters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, subproperty_event_filter.SubpropertyEventFilter) + for i in results) + + pages = list(client.list_subproperty_event_filters(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", [ + analytics_admin.UpdateSubpropertyEventFilterRequest, + dict, +]) +def test_update_subproperty_event_filter_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'subproperty_event_filter': {'name': 'properties/sample1/subpropertyEventFilters/sample2'}} + request_init["subproperty_event_filter"] = {'name': 'properties/sample1/subpropertyEventFilters/sample2', 'apply_to_property': 'apply_to_property_value', 'filter_clauses': [{'filter_clause_type': 1, 'filter_expression': {'or_group': {'filter_expressions': {}}, 'not_expression': {}, 'filter_condition': {'null_filter': True, 'string_filter': {'match_type': 1, 'value': 'value_value', 'case_sensitive': True}, 'field_name': 'field_name_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 = analytics_admin.UpdateSubpropertyEventFilterRequest.meta.fields["subproperty_event_filter"] + + 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["subproperty_event_filter"].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["subproperty_event_filter"][field])): + del request_init["subproperty_event_filter"][field][i][subfield] + else: + del request_init["subproperty_event_filter"][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 = gaa_subproperty_event_filter.SubpropertyEventFilter( + name='name_value', + apply_to_property='apply_to_property_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 = gaa_subproperty_event_filter.SubpropertyEventFilter.pb(return_value) + 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_subproperty_event_filter(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gaa_subproperty_event_filter.SubpropertyEventFilter) + assert response.name == 'name_value' + assert response.apply_to_property == 'apply_to_property_value' + +def test_update_subproperty_event_filter_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_subproperty_event_filter in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_subproperty_event_filter] = mock_rpc + + request = {} + client.update_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_subproperty_event_filter_rest_required_fields(request_type=analytics_admin.UpdateSubpropertyEventFilterRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_subproperty_event_filter._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_subproperty_event_filter._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + # 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 = gaa_subproperty_event_filter.SubpropertyEventFilter.pb(return_value) + 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_subproperty_event_filter(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_subproperty_event_filter_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_subproperty_event_filter._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("subpropertyEventFilter", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_subproperty_event_filter_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_subproperty_event_filter") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_subproperty_event_filter") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateSubpropertyEventFilterRequest.pb(analytics_admin.UpdateSubpropertyEventFilterRequest()) + 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 = gaa_subproperty_event_filter.SubpropertyEventFilter.to_json(gaa_subproperty_event_filter.SubpropertyEventFilter()) + + request = analytics_admin.UpdateSubpropertyEventFilterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gaa_subproperty_event_filter.SubpropertyEventFilter() + + client.update_subproperty_event_filter(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_subproperty_event_filter_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateSubpropertyEventFilterRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'subproperty_event_filter': {'name': 'properties/sample1/subpropertyEventFilters/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_subproperty_event_filter(request) + + +def test_update_subproperty_event_filter_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = gaa_subproperty_event_filter.SubpropertyEventFilter() + + # get arguments that satisfy an http rule for this method + sample_request = {'subproperty_event_filter': {'name': 'properties/sample1/subpropertyEventFilters/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(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 = gaa_subproperty_event_filter.SubpropertyEventFilter.pb(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_subproperty_event_filter(**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/v1alpha/{subproperty_event_filter.name=properties/*/subpropertyEventFilters/*}" % client.transport._host, args[1]) + + +def test_update_subproperty_event_filter_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_subproperty_event_filter( + analytics_admin.UpdateSubpropertyEventFilterRequest(), + subproperty_event_filter=gaa_subproperty_event_filter.SubpropertyEventFilter(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_subproperty_event_filter_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteSubpropertyEventFilterRequest, + dict, +]) +def test_delete_subproperty_event_filter_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/subpropertyEventFilters/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_subproperty_event_filter(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_subproperty_event_filter_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_subproperty_event_filter in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_subproperty_event_filter] = mock_rpc + + request = {} + client.delete_subproperty_event_filter(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_subproperty_event_filter(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_subproperty_event_filter_rest_required_fields(request_type=analytics_admin.DeleteSubpropertyEventFilterRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_subproperty_event_filter._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_subproperty_event_filter._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 = AnalyticsAdminServiceClient( + 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_subproperty_event_filter(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_subproperty_event_filter_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_subproperty_event_filter._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_subproperty_event_filter_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_subproperty_event_filter") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteSubpropertyEventFilterRequest.pb(analytics_admin.DeleteSubpropertyEventFilterRequest()) + 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 = analytics_admin.DeleteSubpropertyEventFilterRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_subproperty_event_filter(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_subproperty_event_filter_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteSubpropertyEventFilterRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/subpropertyEventFilters/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_subproperty_event_filter(request) + + +def test_delete_subproperty_event_filter_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/subpropertyEventFilters/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_subproperty_event_filter(**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/v1alpha/{name=properties/*/subpropertyEventFilters/*}" % client.transport._host, args[1]) + + +def test_delete_subproperty_event_filter_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_subproperty_event_filter( + analytics_admin.DeleteSubpropertyEventFilterRequest(), + name='name_value', + ) + + +def test_delete_subproperty_event_filter_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnalyticsAdminServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AnalyticsAdminServiceClient( + 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 = AnalyticsAdminServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnalyticsAdminServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AnalyticsAdminServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AnalyticsAdminServiceGrpcTransport, + transports.AnalyticsAdminServiceGrpcAsyncIOTransport, + transports.AnalyticsAdminServiceRestTransport, +]) +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 = AnalyticsAdminServiceClient.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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AnalyticsAdminServiceGrpcTransport, + ) + +def test_analytics_admin_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AnalyticsAdminServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_analytics_admin_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.analytics.admin_v1alpha.services.analytics_admin_service.transports.AnalyticsAdminServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AnalyticsAdminServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_account', + 'list_accounts', + 'delete_account', + 'update_account', + 'provision_account_ticket', + 'list_account_summaries', + 'get_property', + 'list_properties', + 'create_property', + 'delete_property', + 'update_property', + 'create_firebase_link', + 'delete_firebase_link', + 'list_firebase_links', + 'get_global_site_tag', + 'create_google_ads_link', + 'update_google_ads_link', + 'delete_google_ads_link', + 'list_google_ads_links', + 'get_data_sharing_settings', + 'get_measurement_protocol_secret', + 'list_measurement_protocol_secrets', + 'create_measurement_protocol_secret', + 'delete_measurement_protocol_secret', + 'update_measurement_protocol_secret', + 'acknowledge_user_data_collection', + 'get_sk_ad_network_conversion_value_schema', + 'create_sk_ad_network_conversion_value_schema', + 'delete_sk_ad_network_conversion_value_schema', + 'update_sk_ad_network_conversion_value_schema', + 'list_sk_ad_network_conversion_value_schemas', + 'search_change_history_events', + 'get_google_signals_settings', + 'update_google_signals_settings', + 'create_conversion_event', + 'update_conversion_event', + 'get_conversion_event', + 'delete_conversion_event', + 'list_conversion_events', + 'create_key_event', + 'update_key_event', + 'get_key_event', + 'delete_key_event', + 'list_key_events', + 'get_display_video360_advertiser_link', + 'list_display_video360_advertiser_links', + 'create_display_video360_advertiser_link', + 'delete_display_video360_advertiser_link', + 'update_display_video360_advertiser_link', + 'get_display_video360_advertiser_link_proposal', + 'list_display_video360_advertiser_link_proposals', + 'create_display_video360_advertiser_link_proposal', + 'delete_display_video360_advertiser_link_proposal', + 'approve_display_video360_advertiser_link_proposal', + 'cancel_display_video360_advertiser_link_proposal', + 'create_custom_dimension', + 'update_custom_dimension', + 'list_custom_dimensions', + 'archive_custom_dimension', + 'get_custom_dimension', + 'create_custom_metric', + 'update_custom_metric', + 'list_custom_metrics', + 'archive_custom_metric', + 'get_custom_metric', + 'get_data_retention_settings', + 'update_data_retention_settings', + 'create_data_stream', + 'delete_data_stream', + 'update_data_stream', + 'list_data_streams', + 'get_data_stream', + 'get_audience', + 'list_audiences', + 'create_audience', + 'update_audience', + 'archive_audience', + 'get_search_ads360_link', + 'list_search_ads360_links', + 'create_search_ads360_link', + 'delete_search_ads360_link', + 'update_search_ads360_link', + 'get_attribution_settings', + 'update_attribution_settings', + 'run_access_report', + 'create_access_binding', + 'get_access_binding', + 'update_access_binding', + 'delete_access_binding', + 'list_access_bindings', + 'batch_create_access_bindings', + 'batch_get_access_bindings', + 'batch_update_access_bindings', + 'batch_delete_access_bindings', + 'get_expanded_data_set', + 'list_expanded_data_sets', + 'create_expanded_data_set', + 'update_expanded_data_set', + 'delete_expanded_data_set', + 'get_channel_group', + 'list_channel_groups', + 'create_channel_group', + 'update_channel_group', + 'delete_channel_group', + 'set_automated_ga4_configuration_opt_out', + 'fetch_automated_ga4_configuration_opt_out', + 'create_big_query_link', + 'get_big_query_link', + 'list_big_query_links', + 'delete_big_query_link', + 'update_big_query_link', + 'get_enhanced_measurement_settings', + 'update_enhanced_measurement_settings', + 'create_connected_site_tag', + 'delete_connected_site_tag', + 'list_connected_site_tags', + 'fetch_connected_ga4_property', + 'get_ad_sense_link', + 'create_ad_sense_link', + 'delete_ad_sense_link', + 'list_ad_sense_links', + 'get_event_create_rule', + 'list_event_create_rules', + 'create_event_create_rule', + 'update_event_create_rule', + 'delete_event_create_rule', + 'get_event_edit_rule', + 'list_event_edit_rules', + 'create_event_edit_rule', + 'update_event_edit_rule', + 'delete_event_edit_rule', + 'reorder_event_edit_rules', + 'update_data_redaction_settings', + 'get_data_redaction_settings', + 'get_calculated_metric', + 'create_calculated_metric', + 'list_calculated_metrics', + 'update_calculated_metric', + 'delete_calculated_metric', + 'create_rollup_property', + 'get_rollup_property_source_link', + 'list_rollup_property_source_links', + 'create_rollup_property_source_link', + 'delete_rollup_property_source_link', + 'provision_subproperty', + 'create_subproperty_event_filter', + 'get_subproperty_event_filter', + 'list_subproperty_event_filters', + 'update_subproperty_event_filter', + 'delete_subproperty_event_filter', + ) + 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_analytics_admin_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.analytics.admin_v1alpha.services.analytics_admin_service.transports.AnalyticsAdminServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnalyticsAdminServiceTransport( + 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/analytics.edit', + 'https://www.googleapis.com/auth/analytics.manage.users', + 'https://www.googleapis.com/auth/analytics.manage.users.readonly', + 'https://www.googleapis.com/auth/analytics.readonly', +), + quota_project_id="octopus", + ) + + +def test_analytics_admin_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.analytics.admin_v1alpha.services.analytics_admin_service.transports.AnalyticsAdminServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnalyticsAdminServiceTransport() + adc.assert_called_once() + + +def test_analytics_admin_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) + AnalyticsAdminServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/analytics.edit', + 'https://www.googleapis.com/auth/analytics.manage.users', + 'https://www.googleapis.com/auth/analytics.manage.users.readonly', + 'https://www.googleapis.com/auth/analytics.readonly', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnalyticsAdminServiceGrpcTransport, + transports.AnalyticsAdminServiceGrpcAsyncIOTransport, + ], +) +def test_analytics_admin_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/analytics.edit', 'https://www.googleapis.com/auth/analytics.manage.users', 'https://www.googleapis.com/auth/analytics.manage.users.readonly', 'https://www.googleapis.com/auth/analytics.readonly',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnalyticsAdminServiceGrpcTransport, + transports.AnalyticsAdminServiceGrpcAsyncIOTransport, + transports.AnalyticsAdminServiceRestTransport, + ], +) +def test_analytics_admin_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.AnalyticsAdminServiceGrpcTransport, grpc_helpers), + (transports.AnalyticsAdminServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_analytics_admin_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( + "analyticsadmin.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/analytics.edit', + 'https://www.googleapis.com/auth/analytics.manage.users', + 'https://www.googleapis.com/auth/analytics.manage.users.readonly', + 'https://www.googleapis.com/auth/analytics.readonly', +), + scopes=["1", "2"], + default_host="analyticsadmin.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AnalyticsAdminServiceGrpcTransport, transports.AnalyticsAdminServiceGrpcAsyncIOTransport]) +def test_analytics_admin_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_analytics_admin_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.AnalyticsAdminServiceRestTransport ( + 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_analytics_admin_service_host_no_port(transport_name): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='analyticsadmin.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'analyticsadmin.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://analyticsadmin.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_analytics_admin_service_host_with_port(transport_name): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='analyticsadmin.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'analyticsadmin.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://analyticsadmin.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_analytics_admin_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AnalyticsAdminServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AnalyticsAdminServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_account._session + session2 = client2.transport.get_account._session + assert session1 != session2 + session1 = client1.transport.list_accounts._session + session2 = client2.transport.list_accounts._session + assert session1 != session2 + session1 = client1.transport.delete_account._session + session2 = client2.transport.delete_account._session + assert session1 != session2 + session1 = client1.transport.update_account._session + session2 = client2.transport.update_account._session + assert session1 != session2 + session1 = client1.transport.provision_account_ticket._session + session2 = client2.transport.provision_account_ticket._session + assert session1 != session2 + session1 = client1.transport.list_account_summaries._session + session2 = client2.transport.list_account_summaries._session + assert session1 != session2 + session1 = client1.transport.get_property._session + session2 = client2.transport.get_property._session + assert session1 != session2 + session1 = client1.transport.list_properties._session + session2 = client2.transport.list_properties._session + assert session1 != session2 + session1 = client1.transport.create_property._session + session2 = client2.transport.create_property._session + assert session1 != session2 + session1 = client1.transport.delete_property._session + session2 = client2.transport.delete_property._session + assert session1 != session2 + session1 = client1.transport.update_property._session + session2 = client2.transport.update_property._session + assert session1 != session2 + session1 = client1.transport.create_firebase_link._session + session2 = client2.transport.create_firebase_link._session + assert session1 != session2 + session1 = client1.transport.delete_firebase_link._session + session2 = client2.transport.delete_firebase_link._session + assert session1 != session2 + session1 = client1.transport.list_firebase_links._session + session2 = client2.transport.list_firebase_links._session + assert session1 != session2 + session1 = client1.transport.get_global_site_tag._session + session2 = client2.transport.get_global_site_tag._session + assert session1 != session2 + session1 = client1.transport.create_google_ads_link._session + session2 = client2.transport.create_google_ads_link._session + assert session1 != session2 + session1 = client1.transport.update_google_ads_link._session + session2 = client2.transport.update_google_ads_link._session + assert session1 != session2 + session1 = client1.transport.delete_google_ads_link._session + session2 = client2.transport.delete_google_ads_link._session + assert session1 != session2 + session1 = client1.transport.list_google_ads_links._session + session2 = client2.transport.list_google_ads_links._session + assert session1 != session2 + session1 = client1.transport.get_data_sharing_settings._session + session2 = client2.transport.get_data_sharing_settings._session + assert session1 != session2 + session1 = client1.transport.get_measurement_protocol_secret._session + session2 = client2.transport.get_measurement_protocol_secret._session + assert session1 != session2 + session1 = client1.transport.list_measurement_protocol_secrets._session + session2 = client2.transport.list_measurement_protocol_secrets._session + assert session1 != session2 + session1 = client1.transport.create_measurement_protocol_secret._session + session2 = client2.transport.create_measurement_protocol_secret._session + assert session1 != session2 + session1 = client1.transport.delete_measurement_protocol_secret._session + session2 = client2.transport.delete_measurement_protocol_secret._session + assert session1 != session2 + session1 = client1.transport.update_measurement_protocol_secret._session + session2 = client2.transport.update_measurement_protocol_secret._session + assert session1 != session2 + session1 = client1.transport.acknowledge_user_data_collection._session + session2 = client2.transport.acknowledge_user_data_collection._session + assert session1 != session2 + session1 = client1.transport.get_sk_ad_network_conversion_value_schema._session + session2 = client2.transport.get_sk_ad_network_conversion_value_schema._session + assert session1 != session2 + session1 = client1.transport.create_sk_ad_network_conversion_value_schema._session + session2 = client2.transport.create_sk_ad_network_conversion_value_schema._session + assert session1 != session2 + session1 = client1.transport.delete_sk_ad_network_conversion_value_schema._session + session2 = client2.transport.delete_sk_ad_network_conversion_value_schema._session + assert session1 != session2 + session1 = client1.transport.update_sk_ad_network_conversion_value_schema._session + session2 = client2.transport.update_sk_ad_network_conversion_value_schema._session + assert session1 != session2 + session1 = client1.transport.list_sk_ad_network_conversion_value_schemas._session + session2 = client2.transport.list_sk_ad_network_conversion_value_schemas._session + assert session1 != session2 + session1 = client1.transport.search_change_history_events._session + session2 = client2.transport.search_change_history_events._session + assert session1 != session2 + session1 = client1.transport.get_google_signals_settings._session + session2 = client2.transport.get_google_signals_settings._session + assert session1 != session2 + session1 = client1.transport.update_google_signals_settings._session + session2 = client2.transport.update_google_signals_settings._session + assert session1 != session2 + session1 = client1.transport.create_conversion_event._session + session2 = client2.transport.create_conversion_event._session + assert session1 != session2 + session1 = client1.transport.update_conversion_event._session + session2 = client2.transport.update_conversion_event._session + assert session1 != session2 + session1 = client1.transport.get_conversion_event._session + session2 = client2.transport.get_conversion_event._session + assert session1 != session2 + session1 = client1.transport.delete_conversion_event._session + session2 = client2.transport.delete_conversion_event._session + assert session1 != session2 + session1 = client1.transport.list_conversion_events._session + session2 = client2.transport.list_conversion_events._session + assert session1 != session2 + session1 = client1.transport.create_key_event._session + session2 = client2.transport.create_key_event._session + assert session1 != session2 + session1 = client1.transport.update_key_event._session + session2 = client2.transport.update_key_event._session + assert session1 != session2 + session1 = client1.transport.get_key_event._session + session2 = client2.transport.get_key_event._session + assert session1 != session2 + session1 = client1.transport.delete_key_event._session + session2 = client2.transport.delete_key_event._session + assert session1 != session2 + session1 = client1.transport.list_key_events._session + session2 = client2.transport.list_key_events._session + assert session1 != session2 + session1 = client1.transport.get_display_video360_advertiser_link._session + session2 = client2.transport.get_display_video360_advertiser_link._session + assert session1 != session2 + session1 = client1.transport.list_display_video360_advertiser_links._session + session2 = client2.transport.list_display_video360_advertiser_links._session + assert session1 != session2 + session1 = client1.transport.create_display_video360_advertiser_link._session + session2 = client2.transport.create_display_video360_advertiser_link._session + assert session1 != session2 + session1 = client1.transport.delete_display_video360_advertiser_link._session + session2 = client2.transport.delete_display_video360_advertiser_link._session + assert session1 != session2 + session1 = client1.transport.update_display_video360_advertiser_link._session + session2 = client2.transport.update_display_video360_advertiser_link._session + assert session1 != session2 + session1 = client1.transport.get_display_video360_advertiser_link_proposal._session + session2 = client2.transport.get_display_video360_advertiser_link_proposal._session + assert session1 != session2 + session1 = client1.transport.list_display_video360_advertiser_link_proposals._session + session2 = client2.transport.list_display_video360_advertiser_link_proposals._session + assert session1 != session2 + session1 = client1.transport.create_display_video360_advertiser_link_proposal._session + session2 = client2.transport.create_display_video360_advertiser_link_proposal._session + assert session1 != session2 + session1 = client1.transport.delete_display_video360_advertiser_link_proposal._session + session2 = client2.transport.delete_display_video360_advertiser_link_proposal._session + assert session1 != session2 + session1 = client1.transport.approve_display_video360_advertiser_link_proposal._session + session2 = client2.transport.approve_display_video360_advertiser_link_proposal._session + assert session1 != session2 + session1 = client1.transport.cancel_display_video360_advertiser_link_proposal._session + session2 = client2.transport.cancel_display_video360_advertiser_link_proposal._session + assert session1 != session2 + session1 = client1.transport.create_custom_dimension._session + session2 = client2.transport.create_custom_dimension._session + assert session1 != session2 + session1 = client1.transport.update_custom_dimension._session + session2 = client2.transport.update_custom_dimension._session + assert session1 != session2 + session1 = client1.transport.list_custom_dimensions._session + session2 = client2.transport.list_custom_dimensions._session + assert session1 != session2 + session1 = client1.transport.archive_custom_dimension._session + session2 = client2.transport.archive_custom_dimension._session + assert session1 != session2 + session1 = client1.transport.get_custom_dimension._session + session2 = client2.transport.get_custom_dimension._session + assert session1 != session2 + session1 = client1.transport.create_custom_metric._session + session2 = client2.transport.create_custom_metric._session + assert session1 != session2 + session1 = client1.transport.update_custom_metric._session + session2 = client2.transport.update_custom_metric._session + assert session1 != session2 + session1 = client1.transport.list_custom_metrics._session + session2 = client2.transport.list_custom_metrics._session + assert session1 != session2 + session1 = client1.transport.archive_custom_metric._session + session2 = client2.transport.archive_custom_metric._session + assert session1 != session2 + session1 = client1.transport.get_custom_metric._session + session2 = client2.transport.get_custom_metric._session + assert session1 != session2 + session1 = client1.transport.get_data_retention_settings._session + session2 = client2.transport.get_data_retention_settings._session + assert session1 != session2 + session1 = client1.transport.update_data_retention_settings._session + session2 = client2.transport.update_data_retention_settings._session + assert session1 != session2 + session1 = client1.transport.create_data_stream._session + session2 = client2.transport.create_data_stream._session + assert session1 != session2 + session1 = client1.transport.delete_data_stream._session + session2 = client2.transport.delete_data_stream._session + assert session1 != session2 + session1 = client1.transport.update_data_stream._session + session2 = client2.transport.update_data_stream._session + assert session1 != session2 + session1 = client1.transport.list_data_streams._session + session2 = client2.transport.list_data_streams._session + assert session1 != session2 + session1 = client1.transport.get_data_stream._session + session2 = client2.transport.get_data_stream._session + assert session1 != session2 + session1 = client1.transport.get_audience._session + session2 = client2.transport.get_audience._session + assert session1 != session2 + session1 = client1.transport.list_audiences._session + session2 = client2.transport.list_audiences._session + assert session1 != session2 + session1 = client1.transport.create_audience._session + session2 = client2.transport.create_audience._session + assert session1 != session2 + session1 = client1.transport.update_audience._session + session2 = client2.transport.update_audience._session + assert session1 != session2 + session1 = client1.transport.archive_audience._session + session2 = client2.transport.archive_audience._session + assert session1 != session2 + session1 = client1.transport.get_search_ads360_link._session + session2 = client2.transport.get_search_ads360_link._session + assert session1 != session2 + session1 = client1.transport.list_search_ads360_links._session + session2 = client2.transport.list_search_ads360_links._session + assert session1 != session2 + session1 = client1.transport.create_search_ads360_link._session + session2 = client2.transport.create_search_ads360_link._session + assert session1 != session2 + session1 = client1.transport.delete_search_ads360_link._session + session2 = client2.transport.delete_search_ads360_link._session + assert session1 != session2 + session1 = client1.transport.update_search_ads360_link._session + session2 = client2.transport.update_search_ads360_link._session + assert session1 != session2 + session1 = client1.transport.get_attribution_settings._session + session2 = client2.transport.get_attribution_settings._session + assert session1 != session2 + session1 = client1.transport.update_attribution_settings._session + session2 = client2.transport.update_attribution_settings._session + assert session1 != session2 + session1 = client1.transport.run_access_report._session + session2 = client2.transport.run_access_report._session + assert session1 != session2 + session1 = client1.transport.create_access_binding._session + session2 = client2.transport.create_access_binding._session + assert session1 != session2 + session1 = client1.transport.get_access_binding._session + session2 = client2.transport.get_access_binding._session + assert session1 != session2 + session1 = client1.transport.update_access_binding._session + session2 = client2.transport.update_access_binding._session + assert session1 != session2 + session1 = client1.transport.delete_access_binding._session + session2 = client2.transport.delete_access_binding._session + assert session1 != session2 + session1 = client1.transport.list_access_bindings._session + session2 = client2.transport.list_access_bindings._session + assert session1 != session2 + session1 = client1.transport.batch_create_access_bindings._session + session2 = client2.transport.batch_create_access_bindings._session + assert session1 != session2 + session1 = client1.transport.batch_get_access_bindings._session + session2 = client2.transport.batch_get_access_bindings._session + assert session1 != session2 + session1 = client1.transport.batch_update_access_bindings._session + session2 = client2.transport.batch_update_access_bindings._session + assert session1 != session2 + session1 = client1.transport.batch_delete_access_bindings._session + session2 = client2.transport.batch_delete_access_bindings._session + assert session1 != session2 + session1 = client1.transport.get_expanded_data_set._session + session2 = client2.transport.get_expanded_data_set._session + assert session1 != session2 + session1 = client1.transport.list_expanded_data_sets._session + session2 = client2.transport.list_expanded_data_sets._session + assert session1 != session2 + session1 = client1.transport.create_expanded_data_set._session + session2 = client2.transport.create_expanded_data_set._session + assert session1 != session2 + session1 = client1.transport.update_expanded_data_set._session + session2 = client2.transport.update_expanded_data_set._session + assert session1 != session2 + session1 = client1.transport.delete_expanded_data_set._session + session2 = client2.transport.delete_expanded_data_set._session + assert session1 != session2 + session1 = client1.transport.get_channel_group._session + session2 = client2.transport.get_channel_group._session + assert session1 != session2 + session1 = client1.transport.list_channel_groups._session + session2 = client2.transport.list_channel_groups._session + assert session1 != session2 + session1 = client1.transport.create_channel_group._session + session2 = client2.transport.create_channel_group._session + assert session1 != session2 + session1 = client1.transport.update_channel_group._session + session2 = client2.transport.update_channel_group._session + assert session1 != session2 + session1 = client1.transport.delete_channel_group._session + session2 = client2.transport.delete_channel_group._session + assert session1 != session2 + session1 = client1.transport.set_automated_ga4_configuration_opt_out._session + session2 = client2.transport.set_automated_ga4_configuration_opt_out._session + assert session1 != session2 + session1 = client1.transport.fetch_automated_ga4_configuration_opt_out._session + session2 = client2.transport.fetch_automated_ga4_configuration_opt_out._session + assert session1 != session2 + session1 = client1.transport.create_big_query_link._session + session2 = client2.transport.create_big_query_link._session + assert session1 != session2 + session1 = client1.transport.get_big_query_link._session + session2 = client2.transport.get_big_query_link._session + assert session1 != session2 + session1 = client1.transport.list_big_query_links._session + session2 = client2.transport.list_big_query_links._session + assert session1 != session2 + session1 = client1.transport.delete_big_query_link._session + session2 = client2.transport.delete_big_query_link._session + assert session1 != session2 + session1 = client1.transport.update_big_query_link._session + session2 = client2.transport.update_big_query_link._session + assert session1 != session2 + session1 = client1.transport.get_enhanced_measurement_settings._session + session2 = client2.transport.get_enhanced_measurement_settings._session + assert session1 != session2 + session1 = client1.transport.update_enhanced_measurement_settings._session + session2 = client2.transport.update_enhanced_measurement_settings._session + assert session1 != session2 + session1 = client1.transport.create_connected_site_tag._session + session2 = client2.transport.create_connected_site_tag._session + assert session1 != session2 + session1 = client1.transport.delete_connected_site_tag._session + session2 = client2.transport.delete_connected_site_tag._session + assert session1 != session2 + session1 = client1.transport.list_connected_site_tags._session + session2 = client2.transport.list_connected_site_tags._session + assert session1 != session2 + session1 = client1.transport.fetch_connected_ga4_property._session + session2 = client2.transport.fetch_connected_ga4_property._session + assert session1 != session2 + session1 = client1.transport.get_ad_sense_link._session + session2 = client2.transport.get_ad_sense_link._session + assert session1 != session2 + session1 = client1.transport.create_ad_sense_link._session + session2 = client2.transport.create_ad_sense_link._session + assert session1 != session2 + session1 = client1.transport.delete_ad_sense_link._session + session2 = client2.transport.delete_ad_sense_link._session + assert session1 != session2 + session1 = client1.transport.list_ad_sense_links._session + session2 = client2.transport.list_ad_sense_links._session + assert session1 != session2 + session1 = client1.transport.get_event_create_rule._session + session2 = client2.transport.get_event_create_rule._session + assert session1 != session2 + session1 = client1.transport.list_event_create_rules._session + session2 = client2.transport.list_event_create_rules._session + assert session1 != session2 + session1 = client1.transport.create_event_create_rule._session + session2 = client2.transport.create_event_create_rule._session + assert session1 != session2 + session1 = client1.transport.update_event_create_rule._session + session2 = client2.transport.update_event_create_rule._session + assert session1 != session2 + session1 = client1.transport.delete_event_create_rule._session + session2 = client2.transport.delete_event_create_rule._session + assert session1 != session2 + session1 = client1.transport.get_event_edit_rule._session + session2 = client2.transport.get_event_edit_rule._session + assert session1 != session2 + session1 = client1.transport.list_event_edit_rules._session + session2 = client2.transport.list_event_edit_rules._session + assert session1 != session2 + session1 = client1.transport.create_event_edit_rule._session + session2 = client2.transport.create_event_edit_rule._session + assert session1 != session2 + session1 = client1.transport.update_event_edit_rule._session + session2 = client2.transport.update_event_edit_rule._session + assert session1 != session2 + session1 = client1.transport.delete_event_edit_rule._session + session2 = client2.transport.delete_event_edit_rule._session + assert session1 != session2 + session1 = client1.transport.reorder_event_edit_rules._session + session2 = client2.transport.reorder_event_edit_rules._session + assert session1 != session2 + session1 = client1.transport.update_data_redaction_settings._session + session2 = client2.transport.update_data_redaction_settings._session + assert session1 != session2 + session1 = client1.transport.get_data_redaction_settings._session + session2 = client2.transport.get_data_redaction_settings._session + assert session1 != session2 + session1 = client1.transport.get_calculated_metric._session + session2 = client2.transport.get_calculated_metric._session + assert session1 != session2 + session1 = client1.transport.create_calculated_metric._session + session2 = client2.transport.create_calculated_metric._session + assert session1 != session2 + session1 = client1.transport.list_calculated_metrics._session + session2 = client2.transport.list_calculated_metrics._session + assert session1 != session2 + session1 = client1.transport.update_calculated_metric._session + session2 = client2.transport.update_calculated_metric._session + assert session1 != session2 + session1 = client1.transport.delete_calculated_metric._session + session2 = client2.transport.delete_calculated_metric._session + assert session1 != session2 + session1 = client1.transport.create_rollup_property._session + session2 = client2.transport.create_rollup_property._session + assert session1 != session2 + session1 = client1.transport.get_rollup_property_source_link._session + session2 = client2.transport.get_rollup_property_source_link._session + assert session1 != session2 + session1 = client1.transport.list_rollup_property_source_links._session + session2 = client2.transport.list_rollup_property_source_links._session + assert session1 != session2 + session1 = client1.transport.create_rollup_property_source_link._session + session2 = client2.transport.create_rollup_property_source_link._session + assert session1 != session2 + session1 = client1.transport.delete_rollup_property_source_link._session + session2 = client2.transport.delete_rollup_property_source_link._session + assert session1 != session2 + session1 = client1.transport.provision_subproperty._session + session2 = client2.transport.provision_subproperty._session + assert session1 != session2 + session1 = client1.transport.create_subproperty_event_filter._session + session2 = client2.transport.create_subproperty_event_filter._session + assert session1 != session2 + session1 = client1.transport.get_subproperty_event_filter._session + session2 = client2.transport.get_subproperty_event_filter._session + assert session1 != session2 + session1 = client1.transport.list_subproperty_event_filters._session + session2 = client2.transport.list_subproperty_event_filters._session + assert session1 != session2 + session1 = client1.transport.update_subproperty_event_filter._session + session2 = client2.transport.update_subproperty_event_filter._session + assert session1 != session2 + session1 = client1.transport.delete_subproperty_event_filter._session + session2 = client2.transport.delete_subproperty_event_filter._session + assert session1 != session2 +def test_analytics_admin_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AnalyticsAdminServiceGrpcTransport( + 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_analytics_admin_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AnalyticsAdminServiceGrpcAsyncIOTransport( + 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.AnalyticsAdminServiceGrpcTransport, transports.AnalyticsAdminServiceGrpcAsyncIOTransport]) +def test_analytics_admin_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.AnalyticsAdminServiceGrpcTransport, transports.AnalyticsAdminServiceGrpcAsyncIOTransport]) +def test_analytics_admin_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_access_binding_path(): + account = "squid" + access_binding = "clam" + expected = "accounts/{account}/accessBindings/{access_binding}".format(account=account, access_binding=access_binding, ) + actual = AnalyticsAdminServiceClient.access_binding_path(account, access_binding) + assert expected == actual + + +def test_parse_access_binding_path(): + expected = { + "account": "whelk", + "access_binding": "octopus", + } + path = AnalyticsAdminServiceClient.access_binding_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_access_binding_path(path) + assert expected == actual + +def test_account_path(): + account = "oyster" + expected = "accounts/{account}".format(account=account, ) + actual = AnalyticsAdminServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "nudibranch", + } + path = AnalyticsAdminServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_account_path(path) + assert expected == actual + +def test_account_summary_path(): + account_summary = "cuttlefish" + expected = "accountSummaries/{account_summary}".format(account_summary=account_summary, ) + actual = AnalyticsAdminServiceClient.account_summary_path(account_summary) + assert expected == actual + + +def test_parse_account_summary_path(): + expected = { + "account_summary": "mussel", + } + path = AnalyticsAdminServiceClient.account_summary_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_account_summary_path(path) + assert expected == actual + +def test_ad_sense_link_path(): + property = "winkle" + adsense_link = "nautilus" + expected = "properties/{property}/adSenseLinks/{adsense_link}".format(property=property, adsense_link=adsense_link, ) + actual = AnalyticsAdminServiceClient.ad_sense_link_path(property, adsense_link) + assert expected == actual + + +def test_parse_ad_sense_link_path(): + expected = { + "property": "scallop", + "adsense_link": "abalone", + } + path = AnalyticsAdminServiceClient.ad_sense_link_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_ad_sense_link_path(path) + assert expected == actual + +def test_attribution_settings_path(): + property = "squid" + expected = "properties/{property}/attributionSettings".format(property=property, ) + actual = AnalyticsAdminServiceClient.attribution_settings_path(property) + assert expected == actual + + +def test_parse_attribution_settings_path(): + expected = { + "property": "clam", + } + path = AnalyticsAdminServiceClient.attribution_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_attribution_settings_path(path) + assert expected == actual + +def test_audience_path(): + property = "whelk" + audience = "octopus" + expected = "properties/{property}/audiences/{audience}".format(property=property, audience=audience, ) + actual = AnalyticsAdminServiceClient.audience_path(property, audience) + assert expected == actual + + +def test_parse_audience_path(): + expected = { + "property": "oyster", + "audience": "nudibranch", + } + path = AnalyticsAdminServiceClient.audience_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_audience_path(path) + assert expected == actual + +def test_big_query_link_path(): + property = "cuttlefish" + bigquery_link = "mussel" + expected = "properties/{property}/bigQueryLinks/{bigquery_link}".format(property=property, bigquery_link=bigquery_link, ) + actual = AnalyticsAdminServiceClient.big_query_link_path(property, bigquery_link) + assert expected == actual + + +def test_parse_big_query_link_path(): + expected = { + "property": "winkle", + "bigquery_link": "nautilus", + } + path = AnalyticsAdminServiceClient.big_query_link_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_big_query_link_path(path) + assert expected == actual + +def test_calculated_metric_path(): + property = "scallop" + calculated_metric = "abalone" + expected = "properties/{property}/calculatedMetrics/{calculated_metric}".format(property=property, calculated_metric=calculated_metric, ) + actual = AnalyticsAdminServiceClient.calculated_metric_path(property, calculated_metric) + assert expected == actual + + +def test_parse_calculated_metric_path(): + expected = { + "property": "squid", + "calculated_metric": "clam", + } + path = AnalyticsAdminServiceClient.calculated_metric_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_calculated_metric_path(path) + assert expected == actual + +def test_channel_group_path(): + property = "whelk" + channel_group = "octopus" + expected = "properties/{property}/channelGroups/{channel_group}".format(property=property, channel_group=channel_group, ) + actual = AnalyticsAdminServiceClient.channel_group_path(property, channel_group) + assert expected == actual + + +def test_parse_channel_group_path(): + expected = { + "property": "oyster", + "channel_group": "nudibranch", + } + path = AnalyticsAdminServiceClient.channel_group_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_channel_group_path(path) + assert expected == actual + +def test_conversion_event_path(): + property = "cuttlefish" + conversion_event = "mussel" + expected = "properties/{property}/conversionEvents/{conversion_event}".format(property=property, conversion_event=conversion_event, ) + actual = AnalyticsAdminServiceClient.conversion_event_path(property, conversion_event) + assert expected == actual + + +def test_parse_conversion_event_path(): + expected = { + "property": "winkle", + "conversion_event": "nautilus", + } + path = AnalyticsAdminServiceClient.conversion_event_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_conversion_event_path(path) + assert expected == actual + +def test_custom_dimension_path(): + property = "scallop" + custom_dimension = "abalone" + expected = "properties/{property}/customDimensions/{custom_dimension}".format(property=property, custom_dimension=custom_dimension, ) + actual = AnalyticsAdminServiceClient.custom_dimension_path(property, custom_dimension) + assert expected == actual + + +def test_parse_custom_dimension_path(): + expected = { + "property": "squid", + "custom_dimension": "clam", + } + path = AnalyticsAdminServiceClient.custom_dimension_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_custom_dimension_path(path) + assert expected == actual + +def test_custom_metric_path(): + property = "whelk" + custom_metric = "octopus" + expected = "properties/{property}/customMetrics/{custom_metric}".format(property=property, custom_metric=custom_metric, ) + actual = AnalyticsAdminServiceClient.custom_metric_path(property, custom_metric) + assert expected == actual + + +def test_parse_custom_metric_path(): + expected = { + "property": "oyster", + "custom_metric": "nudibranch", + } + path = AnalyticsAdminServiceClient.custom_metric_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_custom_metric_path(path) + assert expected == actual + +def test_data_redaction_settings_path(): + property = "cuttlefish" + data_stream = "mussel" + expected = "properties/{property}/dataStreams/{data_stream}/dataRedactionSettings".format(property=property, data_stream=data_stream, ) + actual = AnalyticsAdminServiceClient.data_redaction_settings_path(property, data_stream) + assert expected == actual + + +def test_parse_data_redaction_settings_path(): + expected = { + "property": "winkle", + "data_stream": "nautilus", + } + path = AnalyticsAdminServiceClient.data_redaction_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_data_redaction_settings_path(path) + assert expected == actual + +def test_data_retention_settings_path(): + property = "scallop" + expected = "properties/{property}/dataRetentionSettings".format(property=property, ) + actual = AnalyticsAdminServiceClient.data_retention_settings_path(property) + assert expected == actual + + +def test_parse_data_retention_settings_path(): + expected = { + "property": "abalone", + } + path = AnalyticsAdminServiceClient.data_retention_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_data_retention_settings_path(path) + assert expected == actual + +def test_data_sharing_settings_path(): + account = "squid" + expected = "accounts/{account}/dataSharingSettings".format(account=account, ) + actual = AnalyticsAdminServiceClient.data_sharing_settings_path(account) + assert expected == actual + + +def test_parse_data_sharing_settings_path(): + expected = { + "account": "clam", + } + path = AnalyticsAdminServiceClient.data_sharing_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_data_sharing_settings_path(path) + assert expected == actual + +def test_data_stream_path(): + property = "whelk" + data_stream = "octopus" + expected = "properties/{property}/dataStreams/{data_stream}".format(property=property, data_stream=data_stream, ) + actual = AnalyticsAdminServiceClient.data_stream_path(property, data_stream) + assert expected == actual + + +def test_parse_data_stream_path(): + expected = { + "property": "oyster", + "data_stream": "nudibranch", + } + path = AnalyticsAdminServiceClient.data_stream_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_data_stream_path(path) + assert expected == actual + +def test_display_video360_advertiser_link_path(): + property = "cuttlefish" + display_video_360_advertiser_link = "mussel" + expected = "properties/{property}/displayVideo360AdvertiserLinks/{display_video_360_advertiser_link}".format(property=property, display_video_360_advertiser_link=display_video_360_advertiser_link, ) + actual = AnalyticsAdminServiceClient.display_video360_advertiser_link_path(property, display_video_360_advertiser_link) + assert expected == actual + + +def test_parse_display_video360_advertiser_link_path(): + expected = { + "property": "winkle", + "display_video_360_advertiser_link": "nautilus", + } + path = AnalyticsAdminServiceClient.display_video360_advertiser_link_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_display_video360_advertiser_link_path(path) + assert expected == actual + +def test_display_video360_advertiser_link_proposal_path(): + property = "scallop" + display_video_360_advertiser_link_proposal = "abalone" + expected = "properties/{property}/displayVideo360AdvertiserLinkProposals/{display_video_360_advertiser_link_proposal}".format(property=property, display_video_360_advertiser_link_proposal=display_video_360_advertiser_link_proposal, ) + actual = AnalyticsAdminServiceClient.display_video360_advertiser_link_proposal_path(property, display_video_360_advertiser_link_proposal) + assert expected == actual + + +def test_parse_display_video360_advertiser_link_proposal_path(): + expected = { + "property": "squid", + "display_video_360_advertiser_link_proposal": "clam", + } + path = AnalyticsAdminServiceClient.display_video360_advertiser_link_proposal_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_display_video360_advertiser_link_proposal_path(path) + assert expected == actual + +def test_enhanced_measurement_settings_path(): + property = "whelk" + data_stream = "octopus" + expected = "properties/{property}/dataStreams/{data_stream}/enhancedMeasurementSettings".format(property=property, data_stream=data_stream, ) + actual = AnalyticsAdminServiceClient.enhanced_measurement_settings_path(property, data_stream) + assert expected == actual + + +def test_parse_enhanced_measurement_settings_path(): + expected = { + "property": "oyster", + "data_stream": "nudibranch", + } + path = AnalyticsAdminServiceClient.enhanced_measurement_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_enhanced_measurement_settings_path(path) + assert expected == actual + +def test_event_create_rule_path(): + property = "cuttlefish" + data_stream = "mussel" + event_create_rule = "winkle" + expected = "properties/{property}/dataStreams/{data_stream}/eventCreateRules/{event_create_rule}".format(property=property, data_stream=data_stream, event_create_rule=event_create_rule, ) + actual = AnalyticsAdminServiceClient.event_create_rule_path(property, data_stream, event_create_rule) + assert expected == actual + + +def test_parse_event_create_rule_path(): + expected = { + "property": "nautilus", + "data_stream": "scallop", + "event_create_rule": "abalone", + } + path = AnalyticsAdminServiceClient.event_create_rule_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_event_create_rule_path(path) + assert expected == actual + +def test_event_edit_rule_path(): + property = "squid" + data_stream = "clam" + event_edit_rule = "whelk" + expected = "properties/{property}/dataStreams/{data_stream}/eventEditRules/{event_edit_rule}".format(property=property, data_stream=data_stream, event_edit_rule=event_edit_rule, ) + actual = AnalyticsAdminServiceClient.event_edit_rule_path(property, data_stream, event_edit_rule) + assert expected == actual + + +def test_parse_event_edit_rule_path(): + expected = { + "property": "octopus", + "data_stream": "oyster", + "event_edit_rule": "nudibranch", + } + path = AnalyticsAdminServiceClient.event_edit_rule_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_event_edit_rule_path(path) + assert expected == actual + +def test_expanded_data_set_path(): + property = "cuttlefish" + expanded_data_set = "mussel" + expected = "properties/{property}/expandedDataSets/{expanded_data_set}".format(property=property, expanded_data_set=expanded_data_set, ) + actual = AnalyticsAdminServiceClient.expanded_data_set_path(property, expanded_data_set) + assert expected == actual + + +def test_parse_expanded_data_set_path(): + expected = { + "property": "winkle", + "expanded_data_set": "nautilus", + } + path = AnalyticsAdminServiceClient.expanded_data_set_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_expanded_data_set_path(path) + assert expected == actual + +def test_firebase_link_path(): + property = "scallop" + firebase_link = "abalone" + expected = "properties/{property}/firebaseLinks/{firebase_link}".format(property=property, firebase_link=firebase_link, ) + actual = AnalyticsAdminServiceClient.firebase_link_path(property, firebase_link) + assert expected == actual + + +def test_parse_firebase_link_path(): + expected = { + "property": "squid", + "firebase_link": "clam", + } + path = AnalyticsAdminServiceClient.firebase_link_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_firebase_link_path(path) + assert expected == actual + +def test_global_site_tag_path(): + property = "whelk" + data_stream = "octopus" + expected = "properties/{property}/dataStreams/{data_stream}/globalSiteTag".format(property=property, data_stream=data_stream, ) + actual = AnalyticsAdminServiceClient.global_site_tag_path(property, data_stream) + assert expected == actual + + +def test_parse_global_site_tag_path(): + expected = { + "property": "oyster", + "data_stream": "nudibranch", + } + path = AnalyticsAdminServiceClient.global_site_tag_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_global_site_tag_path(path) + assert expected == actual + +def test_google_ads_link_path(): + property = "cuttlefish" + google_ads_link = "mussel" + expected = "properties/{property}/googleAdsLinks/{google_ads_link}".format(property=property, google_ads_link=google_ads_link, ) + actual = AnalyticsAdminServiceClient.google_ads_link_path(property, google_ads_link) + assert expected == actual + + +def test_parse_google_ads_link_path(): + expected = { + "property": "winkle", + "google_ads_link": "nautilus", + } + path = AnalyticsAdminServiceClient.google_ads_link_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_google_ads_link_path(path) + assert expected == actual + +def test_google_signals_settings_path(): + property = "scallop" + expected = "properties/{property}/googleSignalsSettings".format(property=property, ) + actual = AnalyticsAdminServiceClient.google_signals_settings_path(property) + assert expected == actual + + +def test_parse_google_signals_settings_path(): + expected = { + "property": "abalone", + } + path = AnalyticsAdminServiceClient.google_signals_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_google_signals_settings_path(path) + assert expected == actual + +def test_key_event_path(): + property = "squid" + key_event = "clam" + expected = "properties/{property}/keyEvents/{key_event}".format(property=property, key_event=key_event, ) + actual = AnalyticsAdminServiceClient.key_event_path(property, key_event) + assert expected == actual + + +def test_parse_key_event_path(): + expected = { + "property": "whelk", + "key_event": "octopus", + } + path = AnalyticsAdminServiceClient.key_event_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_key_event_path(path) + assert expected == actual + +def test_measurement_protocol_secret_path(): + property = "oyster" + data_stream = "nudibranch" + measurement_protocol_secret = "cuttlefish" + expected = "properties/{property}/dataStreams/{data_stream}/measurementProtocolSecrets/{measurement_protocol_secret}".format(property=property, data_stream=data_stream, measurement_protocol_secret=measurement_protocol_secret, ) + actual = AnalyticsAdminServiceClient.measurement_protocol_secret_path(property, data_stream, measurement_protocol_secret) + assert expected == actual + + +def test_parse_measurement_protocol_secret_path(): + expected = { + "property": "mussel", + "data_stream": "winkle", + "measurement_protocol_secret": "nautilus", + } + path = AnalyticsAdminServiceClient.measurement_protocol_secret_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_measurement_protocol_secret_path(path) + assert expected == actual + +def test_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AnalyticsAdminServiceClient.organization_path(organization) + assert expected == actual + + +def test_parse_organization_path(): + expected = { + "organization": "abalone", + } + path = AnalyticsAdminServiceClient.organization_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_organization_path(path) + assert expected == actual + +def test_property_path(): + property = "squid" + expected = "properties/{property}".format(property=property, ) + actual = AnalyticsAdminServiceClient.property_path(property) + assert expected == actual + + +def test_parse_property_path(): + expected = { + "property": "clam", + } + path = AnalyticsAdminServiceClient.property_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_property_path(path) + assert expected == actual + +def test_rollup_property_source_link_path(): + property = "whelk" + rollup_property_source_link = "octopus" + expected = "properties/{property}/rollupPropertySourceLinks/{rollup_property_source_link}".format(property=property, rollup_property_source_link=rollup_property_source_link, ) + actual = AnalyticsAdminServiceClient.rollup_property_source_link_path(property, rollup_property_source_link) + assert expected == actual + + +def test_parse_rollup_property_source_link_path(): + expected = { + "property": "oyster", + "rollup_property_source_link": "nudibranch", + } + path = AnalyticsAdminServiceClient.rollup_property_source_link_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_rollup_property_source_link_path(path) + assert expected == actual + +def test_search_ads360_link_path(): + property = "cuttlefish" + search_ads_360_link = "mussel" + expected = "properties/{property}/searchAds360Links/{search_ads_360_link}".format(property=property, search_ads_360_link=search_ads_360_link, ) + actual = AnalyticsAdminServiceClient.search_ads360_link_path(property, search_ads_360_link) + assert expected == actual + + +def test_parse_search_ads360_link_path(): + expected = { + "property": "winkle", + "search_ads_360_link": "nautilus", + } + path = AnalyticsAdminServiceClient.search_ads360_link_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_search_ads360_link_path(path) + assert expected == actual + +def test_sk_ad_network_conversion_value_schema_path(): + property = "scallop" + data_stream = "abalone" + skadnetwork_conversion_value_schema = "squid" + expected = "properties/{property}/dataStreams/{data_stream}/sKAdNetworkConversionValueSchema/{skadnetwork_conversion_value_schema}".format(property=property, data_stream=data_stream, skadnetwork_conversion_value_schema=skadnetwork_conversion_value_schema, ) + actual = AnalyticsAdminServiceClient.sk_ad_network_conversion_value_schema_path(property, data_stream, skadnetwork_conversion_value_schema) + assert expected == actual + + +def test_parse_sk_ad_network_conversion_value_schema_path(): + expected = { + "property": "clam", + "data_stream": "whelk", + "skadnetwork_conversion_value_schema": "octopus", + } + path = AnalyticsAdminServiceClient.sk_ad_network_conversion_value_schema_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_sk_ad_network_conversion_value_schema_path(path) + assert expected == actual + +def test_subproperty_event_filter_path(): + property = "oyster" + sub_property_event_filter = "nudibranch" + expected = "properties/{property}/subpropertyEventFilters/{sub_property_event_filter}".format(property=property, sub_property_event_filter=sub_property_event_filter, ) + actual = AnalyticsAdminServiceClient.subproperty_event_filter_path(property, sub_property_event_filter) + assert expected == actual + + +def test_parse_subproperty_event_filter_path(): + expected = { + "property": "cuttlefish", + "sub_property_event_filter": "mussel", + } + path = AnalyticsAdminServiceClient.subproperty_event_filter_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_subproperty_event_filter_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AnalyticsAdminServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = AnalyticsAdminServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format(folder=folder, ) + actual = AnalyticsAdminServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = AnalyticsAdminServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AnalyticsAdminServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = AnalyticsAdminServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format(project=project, ) + actual = AnalyticsAdminServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = AnalyticsAdminServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AnalyticsAdminServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = AnalyticsAdminServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.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.AnalyticsAdminServiceTransport, '_prep_wrapped_messages') as prep: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AnalyticsAdminServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AnalyticsAdminServiceClient.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 = AnalyticsAdminServiceAsyncClient( + 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 = AnalyticsAdminServiceClient( + 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 = AnalyticsAdminServiceClient( + 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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/.coveragerc b/owl-bot-staging/google-analytics-admin/v1beta/.coveragerc new file mode 100644 index 000000000000..9d9c116c67f8 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/analytics/admin/__init__.py + google/analytics/admin/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-analytics-admin/v1beta/.flake8 b/owl-bot-staging/google-analytics-admin/v1beta/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/.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-analytics-admin/v1beta/MANIFEST.in b/owl-bot-staging/google-analytics-admin/v1beta/MANIFEST.in new file mode 100644 index 000000000000..9292cc0f23a5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/analytics/admin *.py +recursive-include google/analytics/admin_v1beta *.py diff --git a/owl-bot-staging/google-analytics-admin/v1beta/README.rst b/owl-bot-staging/google-analytics-admin/v1beta/README.rst new file mode 100644 index 000000000000..890880fac92c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Analytics Admin 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 Analytics Admin 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-analytics-admin/v1beta/docs/_static/custom.css b/owl-bot-staging/google-analytics-admin/v1beta/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-analytics-admin/v1beta/docs/admin_v1beta/analytics_admin_service.rst b/owl-bot-staging/google-analytics-admin/v1beta/docs/admin_v1beta/analytics_admin_service.rst new file mode 100644 index 000000000000..aca3ba6d5977 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/docs/admin_v1beta/analytics_admin_service.rst @@ -0,0 +1,10 @@ +AnalyticsAdminService +--------------------------------------- + +.. automodule:: google.analytics.admin_v1beta.services.analytics_admin_service + :members: + :inherited-members: + +.. automodule:: google.analytics.admin_v1beta.services.analytics_admin_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-analytics-admin/v1beta/docs/admin_v1beta/services_.rst b/owl-bot-staging/google-analytics-admin/v1beta/docs/admin_v1beta/services_.rst new file mode 100644 index 000000000000..9c078ea8475e --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/docs/admin_v1beta/services_.rst @@ -0,0 +1,6 @@ +Services for Google Analytics Admin v1beta API +============================================== +.. toctree:: + :maxdepth: 2 + + analytics_admin_service diff --git a/owl-bot-staging/google-analytics-admin/v1beta/docs/admin_v1beta/types_.rst b/owl-bot-staging/google-analytics-admin/v1beta/docs/admin_v1beta/types_.rst new file mode 100644 index 000000000000..8c7a1227ebe5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/docs/admin_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Analytics Admin v1beta API +=========================================== + +.. automodule:: google.analytics.admin_v1beta.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-analytics-admin/v1beta/docs/conf.py b/owl-bot-staging/google-analytics-admin/v1beta/docs/conf.py new file mode 100644 index 000000000000..184d93bfb9e6 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/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-analytics-admin 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-analytics-admin" +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 Analytics 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-analytics-admin-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-analytics-admin.tex", + u"google-analytics-admin 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-analytics-admin", + u"Google Analytics Admin 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-analytics-admin", + u"google-analytics-admin Documentation", + author, + "google-analytics-admin", + "GAPIC library for Google Analytics Admin 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-analytics-admin/v1beta/docs/index.rst b/owl-bot-staging/google-analytics-admin/v1beta/docs/index.rst new file mode 100644 index 000000000000..f8238f718109 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + admin_v1beta/services + admin_v1beta/types diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin/__init__.py new file mode 100644 index 000000000000..4a1d52190bcf --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin/__init__.py @@ -0,0 +1,247 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.analytics.admin_v1beta.services.analytics_admin_service.client import AnalyticsAdminServiceClient +from google.analytics.admin_v1beta.services.analytics_admin_service.async_client import AnalyticsAdminServiceAsyncClient + +from google.analytics.admin_v1beta.types.access_report import AccessBetweenFilter +from google.analytics.admin_v1beta.types.access_report import AccessDateRange +from google.analytics.admin_v1beta.types.access_report import AccessDimension +from google.analytics.admin_v1beta.types.access_report import AccessDimensionHeader +from google.analytics.admin_v1beta.types.access_report import AccessDimensionValue +from google.analytics.admin_v1beta.types.access_report import AccessFilter +from google.analytics.admin_v1beta.types.access_report import AccessFilterExpression +from google.analytics.admin_v1beta.types.access_report import AccessFilterExpressionList +from google.analytics.admin_v1beta.types.access_report import AccessInListFilter +from google.analytics.admin_v1beta.types.access_report import AccessMetric +from google.analytics.admin_v1beta.types.access_report import AccessMetricHeader +from google.analytics.admin_v1beta.types.access_report import AccessMetricValue +from google.analytics.admin_v1beta.types.access_report import AccessNumericFilter +from google.analytics.admin_v1beta.types.access_report import AccessOrderBy +from google.analytics.admin_v1beta.types.access_report import AccessQuota +from google.analytics.admin_v1beta.types.access_report import AccessQuotaStatus +from google.analytics.admin_v1beta.types.access_report import AccessRow +from google.analytics.admin_v1beta.types.access_report import AccessStringFilter +from google.analytics.admin_v1beta.types.access_report import NumericValue +from google.analytics.admin_v1beta.types.analytics_admin import AcknowledgeUserDataCollectionRequest +from google.analytics.admin_v1beta.types.analytics_admin import AcknowledgeUserDataCollectionResponse +from google.analytics.admin_v1beta.types.analytics_admin import ArchiveCustomDimensionRequest +from google.analytics.admin_v1beta.types.analytics_admin import ArchiveCustomMetricRequest +from google.analytics.admin_v1beta.types.analytics_admin import CreateConversionEventRequest +from google.analytics.admin_v1beta.types.analytics_admin import CreateCustomDimensionRequest +from google.analytics.admin_v1beta.types.analytics_admin import CreateCustomMetricRequest +from google.analytics.admin_v1beta.types.analytics_admin import CreateDataStreamRequest +from google.analytics.admin_v1beta.types.analytics_admin import CreateFirebaseLinkRequest +from google.analytics.admin_v1beta.types.analytics_admin import CreateGoogleAdsLinkRequest +from google.analytics.admin_v1beta.types.analytics_admin import CreateKeyEventRequest +from google.analytics.admin_v1beta.types.analytics_admin import CreateMeasurementProtocolSecretRequest +from google.analytics.admin_v1beta.types.analytics_admin import CreatePropertyRequest +from google.analytics.admin_v1beta.types.analytics_admin import DeleteAccountRequest +from google.analytics.admin_v1beta.types.analytics_admin import DeleteConversionEventRequest +from google.analytics.admin_v1beta.types.analytics_admin import DeleteDataStreamRequest +from google.analytics.admin_v1beta.types.analytics_admin import DeleteFirebaseLinkRequest +from google.analytics.admin_v1beta.types.analytics_admin import DeleteGoogleAdsLinkRequest +from google.analytics.admin_v1beta.types.analytics_admin import DeleteKeyEventRequest +from google.analytics.admin_v1beta.types.analytics_admin import DeleteMeasurementProtocolSecretRequest +from google.analytics.admin_v1beta.types.analytics_admin import DeletePropertyRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetAccountRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetConversionEventRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetCustomDimensionRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetCustomMetricRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetDataRetentionSettingsRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetDataSharingSettingsRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetDataStreamRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetKeyEventRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetMeasurementProtocolSecretRequest +from google.analytics.admin_v1beta.types.analytics_admin import GetPropertyRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListAccountsRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListAccountsResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListAccountSummariesRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListAccountSummariesResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListConversionEventsRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListConversionEventsResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListCustomDimensionsRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListCustomDimensionsResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListCustomMetricsRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListCustomMetricsResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListDataStreamsRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListDataStreamsResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListFirebaseLinksRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListFirebaseLinksResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListGoogleAdsLinksRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListGoogleAdsLinksResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListKeyEventsRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListKeyEventsResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListMeasurementProtocolSecretsRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListMeasurementProtocolSecretsResponse +from google.analytics.admin_v1beta.types.analytics_admin import ListPropertiesRequest +from google.analytics.admin_v1beta.types.analytics_admin import ListPropertiesResponse +from google.analytics.admin_v1beta.types.analytics_admin import ProvisionAccountTicketRequest +from google.analytics.admin_v1beta.types.analytics_admin import ProvisionAccountTicketResponse +from google.analytics.admin_v1beta.types.analytics_admin import RunAccessReportRequest +from google.analytics.admin_v1beta.types.analytics_admin import RunAccessReportResponse +from google.analytics.admin_v1beta.types.analytics_admin import SearchChangeHistoryEventsRequest +from google.analytics.admin_v1beta.types.analytics_admin import SearchChangeHistoryEventsResponse +from google.analytics.admin_v1beta.types.analytics_admin import UpdateAccountRequest +from google.analytics.admin_v1beta.types.analytics_admin import UpdateConversionEventRequest +from google.analytics.admin_v1beta.types.analytics_admin import UpdateCustomDimensionRequest +from google.analytics.admin_v1beta.types.analytics_admin import UpdateCustomMetricRequest +from google.analytics.admin_v1beta.types.analytics_admin import UpdateDataRetentionSettingsRequest +from google.analytics.admin_v1beta.types.analytics_admin import UpdateDataStreamRequest +from google.analytics.admin_v1beta.types.analytics_admin import UpdateGoogleAdsLinkRequest +from google.analytics.admin_v1beta.types.analytics_admin import UpdateKeyEventRequest +from google.analytics.admin_v1beta.types.analytics_admin import UpdateMeasurementProtocolSecretRequest +from google.analytics.admin_v1beta.types.analytics_admin import UpdatePropertyRequest +from google.analytics.admin_v1beta.types.resources import Account +from google.analytics.admin_v1beta.types.resources import AccountSummary +from google.analytics.admin_v1beta.types.resources import ChangeHistoryChange +from google.analytics.admin_v1beta.types.resources import ChangeHistoryEvent +from google.analytics.admin_v1beta.types.resources import ConversionEvent +from google.analytics.admin_v1beta.types.resources import CustomDimension +from google.analytics.admin_v1beta.types.resources import CustomMetric +from google.analytics.admin_v1beta.types.resources import DataRetentionSettings +from google.analytics.admin_v1beta.types.resources import DataSharingSettings +from google.analytics.admin_v1beta.types.resources import DataStream +from google.analytics.admin_v1beta.types.resources import FirebaseLink +from google.analytics.admin_v1beta.types.resources import GoogleAdsLink +from google.analytics.admin_v1beta.types.resources import KeyEvent +from google.analytics.admin_v1beta.types.resources import MeasurementProtocolSecret +from google.analytics.admin_v1beta.types.resources import Property +from google.analytics.admin_v1beta.types.resources import PropertySummary +from google.analytics.admin_v1beta.types.resources import ActionType +from google.analytics.admin_v1beta.types.resources import ActorType +from google.analytics.admin_v1beta.types.resources import ChangeHistoryResourceType +from google.analytics.admin_v1beta.types.resources import IndustryCategory +from google.analytics.admin_v1beta.types.resources import PropertyType +from google.analytics.admin_v1beta.types.resources import ServiceLevel + +__all__ = ('AnalyticsAdminServiceClient', + 'AnalyticsAdminServiceAsyncClient', + 'AccessBetweenFilter', + 'AccessDateRange', + 'AccessDimension', + 'AccessDimensionHeader', + 'AccessDimensionValue', + 'AccessFilter', + 'AccessFilterExpression', + 'AccessFilterExpressionList', + 'AccessInListFilter', + 'AccessMetric', + 'AccessMetricHeader', + 'AccessMetricValue', + 'AccessNumericFilter', + 'AccessOrderBy', + 'AccessQuota', + 'AccessQuotaStatus', + 'AccessRow', + 'AccessStringFilter', + 'NumericValue', + 'AcknowledgeUserDataCollectionRequest', + 'AcknowledgeUserDataCollectionResponse', + 'ArchiveCustomDimensionRequest', + 'ArchiveCustomMetricRequest', + 'CreateConversionEventRequest', + 'CreateCustomDimensionRequest', + 'CreateCustomMetricRequest', + 'CreateDataStreamRequest', + 'CreateFirebaseLinkRequest', + 'CreateGoogleAdsLinkRequest', + 'CreateKeyEventRequest', + 'CreateMeasurementProtocolSecretRequest', + 'CreatePropertyRequest', + 'DeleteAccountRequest', + 'DeleteConversionEventRequest', + 'DeleteDataStreamRequest', + 'DeleteFirebaseLinkRequest', + 'DeleteGoogleAdsLinkRequest', + 'DeleteKeyEventRequest', + 'DeleteMeasurementProtocolSecretRequest', + 'DeletePropertyRequest', + 'GetAccountRequest', + 'GetConversionEventRequest', + 'GetCustomDimensionRequest', + 'GetCustomMetricRequest', + 'GetDataRetentionSettingsRequest', + 'GetDataSharingSettingsRequest', + 'GetDataStreamRequest', + 'GetKeyEventRequest', + 'GetMeasurementProtocolSecretRequest', + 'GetPropertyRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListAccountSummariesRequest', + 'ListAccountSummariesResponse', + 'ListConversionEventsRequest', + 'ListConversionEventsResponse', + 'ListCustomDimensionsRequest', + 'ListCustomDimensionsResponse', + 'ListCustomMetricsRequest', + 'ListCustomMetricsResponse', + 'ListDataStreamsRequest', + 'ListDataStreamsResponse', + 'ListFirebaseLinksRequest', + 'ListFirebaseLinksResponse', + 'ListGoogleAdsLinksRequest', + 'ListGoogleAdsLinksResponse', + 'ListKeyEventsRequest', + 'ListKeyEventsResponse', + 'ListMeasurementProtocolSecretsRequest', + 'ListMeasurementProtocolSecretsResponse', + 'ListPropertiesRequest', + 'ListPropertiesResponse', + 'ProvisionAccountTicketRequest', + 'ProvisionAccountTicketResponse', + 'RunAccessReportRequest', + 'RunAccessReportResponse', + 'SearchChangeHistoryEventsRequest', + 'SearchChangeHistoryEventsResponse', + 'UpdateAccountRequest', + 'UpdateConversionEventRequest', + 'UpdateCustomDimensionRequest', + 'UpdateCustomMetricRequest', + 'UpdateDataRetentionSettingsRequest', + 'UpdateDataStreamRequest', + 'UpdateGoogleAdsLinkRequest', + 'UpdateKeyEventRequest', + 'UpdateMeasurementProtocolSecretRequest', + 'UpdatePropertyRequest', + 'Account', + 'AccountSummary', + 'ChangeHistoryChange', + 'ChangeHistoryEvent', + 'ConversionEvent', + 'CustomDimension', + 'CustomMetric', + 'DataRetentionSettings', + 'DataSharingSettings', + 'DataStream', + 'FirebaseLink', + 'GoogleAdsLink', + 'KeyEvent', + 'MeasurementProtocolSecret', + 'Property', + 'PropertySummary', + 'ActionType', + 'ActorType', + 'ChangeHistoryResourceType', + 'IndustryCategory', + 'PropertyType', + 'ServiceLevel', +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin/gapic_version.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin/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-analytics-admin/v1beta/google/analytics/admin/py.typed b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin/py.typed new file mode 100644 index 000000000000..3b7eb1470672 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-analytics-admin package uses inline types. diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/__init__.py new file mode 100644 index 000000000000..e13799de7e6e --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/__init__.py @@ -0,0 +1,248 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.analytics_admin_service import AnalyticsAdminServiceClient +from .services.analytics_admin_service import AnalyticsAdminServiceAsyncClient + +from .types.access_report import AccessBetweenFilter +from .types.access_report import AccessDateRange +from .types.access_report import AccessDimension +from .types.access_report import AccessDimensionHeader +from .types.access_report import AccessDimensionValue +from .types.access_report import AccessFilter +from .types.access_report import AccessFilterExpression +from .types.access_report import AccessFilterExpressionList +from .types.access_report import AccessInListFilter +from .types.access_report import AccessMetric +from .types.access_report import AccessMetricHeader +from .types.access_report import AccessMetricValue +from .types.access_report import AccessNumericFilter +from .types.access_report import AccessOrderBy +from .types.access_report import AccessQuota +from .types.access_report import AccessQuotaStatus +from .types.access_report import AccessRow +from .types.access_report import AccessStringFilter +from .types.access_report import NumericValue +from .types.analytics_admin import AcknowledgeUserDataCollectionRequest +from .types.analytics_admin import AcknowledgeUserDataCollectionResponse +from .types.analytics_admin import ArchiveCustomDimensionRequest +from .types.analytics_admin import ArchiveCustomMetricRequest +from .types.analytics_admin import CreateConversionEventRequest +from .types.analytics_admin import CreateCustomDimensionRequest +from .types.analytics_admin import CreateCustomMetricRequest +from .types.analytics_admin import CreateDataStreamRequest +from .types.analytics_admin import CreateFirebaseLinkRequest +from .types.analytics_admin import CreateGoogleAdsLinkRequest +from .types.analytics_admin import CreateKeyEventRequest +from .types.analytics_admin import CreateMeasurementProtocolSecretRequest +from .types.analytics_admin import CreatePropertyRequest +from .types.analytics_admin import DeleteAccountRequest +from .types.analytics_admin import DeleteConversionEventRequest +from .types.analytics_admin import DeleteDataStreamRequest +from .types.analytics_admin import DeleteFirebaseLinkRequest +from .types.analytics_admin import DeleteGoogleAdsLinkRequest +from .types.analytics_admin import DeleteKeyEventRequest +from .types.analytics_admin import DeleteMeasurementProtocolSecretRequest +from .types.analytics_admin import DeletePropertyRequest +from .types.analytics_admin import GetAccountRequest +from .types.analytics_admin import GetConversionEventRequest +from .types.analytics_admin import GetCustomDimensionRequest +from .types.analytics_admin import GetCustomMetricRequest +from .types.analytics_admin import GetDataRetentionSettingsRequest +from .types.analytics_admin import GetDataSharingSettingsRequest +from .types.analytics_admin import GetDataStreamRequest +from .types.analytics_admin import GetKeyEventRequest +from .types.analytics_admin import GetMeasurementProtocolSecretRequest +from .types.analytics_admin import GetPropertyRequest +from .types.analytics_admin import ListAccountsRequest +from .types.analytics_admin import ListAccountsResponse +from .types.analytics_admin import ListAccountSummariesRequest +from .types.analytics_admin import ListAccountSummariesResponse +from .types.analytics_admin import ListConversionEventsRequest +from .types.analytics_admin import ListConversionEventsResponse +from .types.analytics_admin import ListCustomDimensionsRequest +from .types.analytics_admin import ListCustomDimensionsResponse +from .types.analytics_admin import ListCustomMetricsRequest +from .types.analytics_admin import ListCustomMetricsResponse +from .types.analytics_admin import ListDataStreamsRequest +from .types.analytics_admin import ListDataStreamsResponse +from .types.analytics_admin import ListFirebaseLinksRequest +from .types.analytics_admin import ListFirebaseLinksResponse +from .types.analytics_admin import ListGoogleAdsLinksRequest +from .types.analytics_admin import ListGoogleAdsLinksResponse +from .types.analytics_admin import ListKeyEventsRequest +from .types.analytics_admin import ListKeyEventsResponse +from .types.analytics_admin import ListMeasurementProtocolSecretsRequest +from .types.analytics_admin import ListMeasurementProtocolSecretsResponse +from .types.analytics_admin import ListPropertiesRequest +from .types.analytics_admin import ListPropertiesResponse +from .types.analytics_admin import ProvisionAccountTicketRequest +from .types.analytics_admin import ProvisionAccountTicketResponse +from .types.analytics_admin import RunAccessReportRequest +from .types.analytics_admin import RunAccessReportResponse +from .types.analytics_admin import SearchChangeHistoryEventsRequest +from .types.analytics_admin import SearchChangeHistoryEventsResponse +from .types.analytics_admin import UpdateAccountRequest +from .types.analytics_admin import UpdateConversionEventRequest +from .types.analytics_admin import UpdateCustomDimensionRequest +from .types.analytics_admin import UpdateCustomMetricRequest +from .types.analytics_admin import UpdateDataRetentionSettingsRequest +from .types.analytics_admin import UpdateDataStreamRequest +from .types.analytics_admin import UpdateGoogleAdsLinkRequest +from .types.analytics_admin import UpdateKeyEventRequest +from .types.analytics_admin import UpdateMeasurementProtocolSecretRequest +from .types.analytics_admin import UpdatePropertyRequest +from .types.resources import Account +from .types.resources import AccountSummary +from .types.resources import ChangeHistoryChange +from .types.resources import ChangeHistoryEvent +from .types.resources import ConversionEvent +from .types.resources import CustomDimension +from .types.resources import CustomMetric +from .types.resources import DataRetentionSettings +from .types.resources import DataSharingSettings +from .types.resources import DataStream +from .types.resources import FirebaseLink +from .types.resources import GoogleAdsLink +from .types.resources import KeyEvent +from .types.resources import MeasurementProtocolSecret +from .types.resources import Property +from .types.resources import PropertySummary +from .types.resources import ActionType +from .types.resources import ActorType +from .types.resources import ChangeHistoryResourceType +from .types.resources import IndustryCategory +from .types.resources import PropertyType +from .types.resources import ServiceLevel + +__all__ = ( + 'AnalyticsAdminServiceAsyncClient', +'AccessBetweenFilter', +'AccessDateRange', +'AccessDimension', +'AccessDimensionHeader', +'AccessDimensionValue', +'AccessFilter', +'AccessFilterExpression', +'AccessFilterExpressionList', +'AccessInListFilter', +'AccessMetric', +'AccessMetricHeader', +'AccessMetricValue', +'AccessNumericFilter', +'AccessOrderBy', +'AccessQuota', +'AccessQuotaStatus', +'AccessRow', +'AccessStringFilter', +'Account', +'AccountSummary', +'AcknowledgeUserDataCollectionRequest', +'AcknowledgeUserDataCollectionResponse', +'ActionType', +'ActorType', +'AnalyticsAdminServiceClient', +'ArchiveCustomDimensionRequest', +'ArchiveCustomMetricRequest', +'ChangeHistoryChange', +'ChangeHistoryEvent', +'ChangeHistoryResourceType', +'ConversionEvent', +'CreateConversionEventRequest', +'CreateCustomDimensionRequest', +'CreateCustomMetricRequest', +'CreateDataStreamRequest', +'CreateFirebaseLinkRequest', +'CreateGoogleAdsLinkRequest', +'CreateKeyEventRequest', +'CreateMeasurementProtocolSecretRequest', +'CreatePropertyRequest', +'CustomDimension', +'CustomMetric', +'DataRetentionSettings', +'DataSharingSettings', +'DataStream', +'DeleteAccountRequest', +'DeleteConversionEventRequest', +'DeleteDataStreamRequest', +'DeleteFirebaseLinkRequest', +'DeleteGoogleAdsLinkRequest', +'DeleteKeyEventRequest', +'DeleteMeasurementProtocolSecretRequest', +'DeletePropertyRequest', +'FirebaseLink', +'GetAccountRequest', +'GetConversionEventRequest', +'GetCustomDimensionRequest', +'GetCustomMetricRequest', +'GetDataRetentionSettingsRequest', +'GetDataSharingSettingsRequest', +'GetDataStreamRequest', +'GetKeyEventRequest', +'GetMeasurementProtocolSecretRequest', +'GetPropertyRequest', +'GoogleAdsLink', +'IndustryCategory', +'KeyEvent', +'ListAccountSummariesRequest', +'ListAccountSummariesResponse', +'ListAccountsRequest', +'ListAccountsResponse', +'ListConversionEventsRequest', +'ListConversionEventsResponse', +'ListCustomDimensionsRequest', +'ListCustomDimensionsResponse', +'ListCustomMetricsRequest', +'ListCustomMetricsResponse', +'ListDataStreamsRequest', +'ListDataStreamsResponse', +'ListFirebaseLinksRequest', +'ListFirebaseLinksResponse', +'ListGoogleAdsLinksRequest', +'ListGoogleAdsLinksResponse', +'ListKeyEventsRequest', +'ListKeyEventsResponse', +'ListMeasurementProtocolSecretsRequest', +'ListMeasurementProtocolSecretsResponse', +'ListPropertiesRequest', +'ListPropertiesResponse', +'MeasurementProtocolSecret', +'NumericValue', +'Property', +'PropertySummary', +'PropertyType', +'ProvisionAccountTicketRequest', +'ProvisionAccountTicketResponse', +'RunAccessReportRequest', +'RunAccessReportResponse', +'SearchChangeHistoryEventsRequest', +'SearchChangeHistoryEventsResponse', +'ServiceLevel', +'UpdateAccountRequest', +'UpdateConversionEventRequest', +'UpdateCustomDimensionRequest', +'UpdateCustomMetricRequest', +'UpdateDataRetentionSettingsRequest', +'UpdateDataStreamRequest', +'UpdateGoogleAdsLinkRequest', +'UpdateKeyEventRequest', +'UpdateMeasurementProtocolSecretRequest', +'UpdatePropertyRequest', +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/gapic_metadata.json b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..55de62c4133e --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/gapic_metadata.json @@ -0,0 +1,838 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.analytics.admin_v1beta", + "protoPackage": "google.analytics.admin.v1beta", + "schema": "1.0", + "services": { + "AnalyticsAdminService": { + "clients": { + "grpc": { + "libraryClient": "AnalyticsAdminServiceClient", + "rpcs": { + "AcknowledgeUserDataCollection": { + "methods": [ + "acknowledge_user_data_collection" + ] + }, + "ArchiveCustomDimension": { + "methods": [ + "archive_custom_dimension" + ] + }, + "ArchiveCustomMetric": { + "methods": [ + "archive_custom_metric" + ] + }, + "CreateConversionEvent": { + "methods": [ + "create_conversion_event" + ] + }, + "CreateCustomDimension": { + "methods": [ + "create_custom_dimension" + ] + }, + "CreateCustomMetric": { + "methods": [ + "create_custom_metric" + ] + }, + "CreateDataStream": { + "methods": [ + "create_data_stream" + ] + }, + "CreateFirebaseLink": { + "methods": [ + "create_firebase_link" + ] + }, + "CreateGoogleAdsLink": { + "methods": [ + "create_google_ads_link" + ] + }, + "CreateKeyEvent": { + "methods": [ + "create_key_event" + ] + }, + "CreateMeasurementProtocolSecret": { + "methods": [ + "create_measurement_protocol_secret" + ] + }, + "CreateProperty": { + "methods": [ + "create_property" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "DeleteConversionEvent": { + "methods": [ + "delete_conversion_event" + ] + }, + "DeleteDataStream": { + "methods": [ + "delete_data_stream" + ] + }, + "DeleteFirebaseLink": { + "methods": [ + "delete_firebase_link" + ] + }, + "DeleteGoogleAdsLink": { + "methods": [ + "delete_google_ads_link" + ] + }, + "DeleteKeyEvent": { + "methods": [ + "delete_key_event" + ] + }, + "DeleteMeasurementProtocolSecret": { + "methods": [ + "delete_measurement_protocol_secret" + ] + }, + "DeleteProperty": { + "methods": [ + "delete_property" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "GetConversionEvent": { + "methods": [ + "get_conversion_event" + ] + }, + "GetCustomDimension": { + "methods": [ + "get_custom_dimension" + ] + }, + "GetCustomMetric": { + "methods": [ + "get_custom_metric" + ] + }, + "GetDataRetentionSettings": { + "methods": [ + "get_data_retention_settings" + ] + }, + "GetDataSharingSettings": { + "methods": [ + "get_data_sharing_settings" + ] + }, + "GetDataStream": { + "methods": [ + "get_data_stream" + ] + }, + "GetKeyEvent": { + "methods": [ + "get_key_event" + ] + }, + "GetMeasurementProtocolSecret": { + "methods": [ + "get_measurement_protocol_secret" + ] + }, + "GetProperty": { + "methods": [ + "get_property" + ] + }, + "ListAccountSummaries": { + "methods": [ + "list_account_summaries" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListConversionEvents": { + "methods": [ + "list_conversion_events" + ] + }, + "ListCustomDimensions": { + "methods": [ + "list_custom_dimensions" + ] + }, + "ListCustomMetrics": { + "methods": [ + "list_custom_metrics" + ] + }, + "ListDataStreams": { + "methods": [ + "list_data_streams" + ] + }, + "ListFirebaseLinks": { + "methods": [ + "list_firebase_links" + ] + }, + "ListGoogleAdsLinks": { + "methods": [ + "list_google_ads_links" + ] + }, + "ListKeyEvents": { + "methods": [ + "list_key_events" + ] + }, + "ListMeasurementProtocolSecrets": { + "methods": [ + "list_measurement_protocol_secrets" + ] + }, + "ListProperties": { + "methods": [ + "list_properties" + ] + }, + "ProvisionAccountTicket": { + "methods": [ + "provision_account_ticket" + ] + }, + "RunAccessReport": { + "methods": [ + "run_access_report" + ] + }, + "SearchChangeHistoryEvents": { + "methods": [ + "search_change_history_events" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + }, + "UpdateConversionEvent": { + "methods": [ + "update_conversion_event" + ] + }, + "UpdateCustomDimension": { + "methods": [ + "update_custom_dimension" + ] + }, + "UpdateCustomMetric": { + "methods": [ + "update_custom_metric" + ] + }, + "UpdateDataRetentionSettings": { + "methods": [ + "update_data_retention_settings" + ] + }, + "UpdateDataStream": { + "methods": [ + "update_data_stream" + ] + }, + "UpdateGoogleAdsLink": { + "methods": [ + "update_google_ads_link" + ] + }, + "UpdateKeyEvent": { + "methods": [ + "update_key_event" + ] + }, + "UpdateMeasurementProtocolSecret": { + "methods": [ + "update_measurement_protocol_secret" + ] + }, + "UpdateProperty": { + "methods": [ + "update_property" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AnalyticsAdminServiceAsyncClient", + "rpcs": { + "AcknowledgeUserDataCollection": { + "methods": [ + "acknowledge_user_data_collection" + ] + }, + "ArchiveCustomDimension": { + "methods": [ + "archive_custom_dimension" + ] + }, + "ArchiveCustomMetric": { + "methods": [ + "archive_custom_metric" + ] + }, + "CreateConversionEvent": { + "methods": [ + "create_conversion_event" + ] + }, + "CreateCustomDimension": { + "methods": [ + "create_custom_dimension" + ] + }, + "CreateCustomMetric": { + "methods": [ + "create_custom_metric" + ] + }, + "CreateDataStream": { + "methods": [ + "create_data_stream" + ] + }, + "CreateFirebaseLink": { + "methods": [ + "create_firebase_link" + ] + }, + "CreateGoogleAdsLink": { + "methods": [ + "create_google_ads_link" + ] + }, + "CreateKeyEvent": { + "methods": [ + "create_key_event" + ] + }, + "CreateMeasurementProtocolSecret": { + "methods": [ + "create_measurement_protocol_secret" + ] + }, + "CreateProperty": { + "methods": [ + "create_property" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "DeleteConversionEvent": { + "methods": [ + "delete_conversion_event" + ] + }, + "DeleteDataStream": { + "methods": [ + "delete_data_stream" + ] + }, + "DeleteFirebaseLink": { + "methods": [ + "delete_firebase_link" + ] + }, + "DeleteGoogleAdsLink": { + "methods": [ + "delete_google_ads_link" + ] + }, + "DeleteKeyEvent": { + "methods": [ + "delete_key_event" + ] + }, + "DeleteMeasurementProtocolSecret": { + "methods": [ + "delete_measurement_protocol_secret" + ] + }, + "DeleteProperty": { + "methods": [ + "delete_property" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "GetConversionEvent": { + "methods": [ + "get_conversion_event" + ] + }, + "GetCustomDimension": { + "methods": [ + "get_custom_dimension" + ] + }, + "GetCustomMetric": { + "methods": [ + "get_custom_metric" + ] + }, + "GetDataRetentionSettings": { + "methods": [ + "get_data_retention_settings" + ] + }, + "GetDataSharingSettings": { + "methods": [ + "get_data_sharing_settings" + ] + }, + "GetDataStream": { + "methods": [ + "get_data_stream" + ] + }, + "GetKeyEvent": { + "methods": [ + "get_key_event" + ] + }, + "GetMeasurementProtocolSecret": { + "methods": [ + "get_measurement_protocol_secret" + ] + }, + "GetProperty": { + "methods": [ + "get_property" + ] + }, + "ListAccountSummaries": { + "methods": [ + "list_account_summaries" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListConversionEvents": { + "methods": [ + "list_conversion_events" + ] + }, + "ListCustomDimensions": { + "methods": [ + "list_custom_dimensions" + ] + }, + "ListCustomMetrics": { + "methods": [ + "list_custom_metrics" + ] + }, + "ListDataStreams": { + "methods": [ + "list_data_streams" + ] + }, + "ListFirebaseLinks": { + "methods": [ + "list_firebase_links" + ] + }, + "ListGoogleAdsLinks": { + "methods": [ + "list_google_ads_links" + ] + }, + "ListKeyEvents": { + "methods": [ + "list_key_events" + ] + }, + "ListMeasurementProtocolSecrets": { + "methods": [ + "list_measurement_protocol_secrets" + ] + }, + "ListProperties": { + "methods": [ + "list_properties" + ] + }, + "ProvisionAccountTicket": { + "methods": [ + "provision_account_ticket" + ] + }, + "RunAccessReport": { + "methods": [ + "run_access_report" + ] + }, + "SearchChangeHistoryEvents": { + "methods": [ + "search_change_history_events" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + }, + "UpdateConversionEvent": { + "methods": [ + "update_conversion_event" + ] + }, + "UpdateCustomDimension": { + "methods": [ + "update_custom_dimension" + ] + }, + "UpdateCustomMetric": { + "methods": [ + "update_custom_metric" + ] + }, + "UpdateDataRetentionSettings": { + "methods": [ + "update_data_retention_settings" + ] + }, + "UpdateDataStream": { + "methods": [ + "update_data_stream" + ] + }, + "UpdateGoogleAdsLink": { + "methods": [ + "update_google_ads_link" + ] + }, + "UpdateKeyEvent": { + "methods": [ + "update_key_event" + ] + }, + "UpdateMeasurementProtocolSecret": { + "methods": [ + "update_measurement_protocol_secret" + ] + }, + "UpdateProperty": { + "methods": [ + "update_property" + ] + } + } + }, + "rest": { + "libraryClient": "AnalyticsAdminServiceClient", + "rpcs": { + "AcknowledgeUserDataCollection": { + "methods": [ + "acknowledge_user_data_collection" + ] + }, + "ArchiveCustomDimension": { + "methods": [ + "archive_custom_dimension" + ] + }, + "ArchiveCustomMetric": { + "methods": [ + "archive_custom_metric" + ] + }, + "CreateConversionEvent": { + "methods": [ + "create_conversion_event" + ] + }, + "CreateCustomDimension": { + "methods": [ + "create_custom_dimension" + ] + }, + "CreateCustomMetric": { + "methods": [ + "create_custom_metric" + ] + }, + "CreateDataStream": { + "methods": [ + "create_data_stream" + ] + }, + "CreateFirebaseLink": { + "methods": [ + "create_firebase_link" + ] + }, + "CreateGoogleAdsLink": { + "methods": [ + "create_google_ads_link" + ] + }, + "CreateKeyEvent": { + "methods": [ + "create_key_event" + ] + }, + "CreateMeasurementProtocolSecret": { + "methods": [ + "create_measurement_protocol_secret" + ] + }, + "CreateProperty": { + "methods": [ + "create_property" + ] + }, + "DeleteAccount": { + "methods": [ + "delete_account" + ] + }, + "DeleteConversionEvent": { + "methods": [ + "delete_conversion_event" + ] + }, + "DeleteDataStream": { + "methods": [ + "delete_data_stream" + ] + }, + "DeleteFirebaseLink": { + "methods": [ + "delete_firebase_link" + ] + }, + "DeleteGoogleAdsLink": { + "methods": [ + "delete_google_ads_link" + ] + }, + "DeleteKeyEvent": { + "methods": [ + "delete_key_event" + ] + }, + "DeleteMeasurementProtocolSecret": { + "methods": [ + "delete_measurement_protocol_secret" + ] + }, + "DeleteProperty": { + "methods": [ + "delete_property" + ] + }, + "GetAccount": { + "methods": [ + "get_account" + ] + }, + "GetConversionEvent": { + "methods": [ + "get_conversion_event" + ] + }, + "GetCustomDimension": { + "methods": [ + "get_custom_dimension" + ] + }, + "GetCustomMetric": { + "methods": [ + "get_custom_metric" + ] + }, + "GetDataRetentionSettings": { + "methods": [ + "get_data_retention_settings" + ] + }, + "GetDataSharingSettings": { + "methods": [ + "get_data_sharing_settings" + ] + }, + "GetDataStream": { + "methods": [ + "get_data_stream" + ] + }, + "GetKeyEvent": { + "methods": [ + "get_key_event" + ] + }, + "GetMeasurementProtocolSecret": { + "methods": [ + "get_measurement_protocol_secret" + ] + }, + "GetProperty": { + "methods": [ + "get_property" + ] + }, + "ListAccountSummaries": { + "methods": [ + "list_account_summaries" + ] + }, + "ListAccounts": { + "methods": [ + "list_accounts" + ] + }, + "ListConversionEvents": { + "methods": [ + "list_conversion_events" + ] + }, + "ListCustomDimensions": { + "methods": [ + "list_custom_dimensions" + ] + }, + "ListCustomMetrics": { + "methods": [ + "list_custom_metrics" + ] + }, + "ListDataStreams": { + "methods": [ + "list_data_streams" + ] + }, + "ListFirebaseLinks": { + "methods": [ + "list_firebase_links" + ] + }, + "ListGoogleAdsLinks": { + "methods": [ + "list_google_ads_links" + ] + }, + "ListKeyEvents": { + "methods": [ + "list_key_events" + ] + }, + "ListMeasurementProtocolSecrets": { + "methods": [ + "list_measurement_protocol_secrets" + ] + }, + "ListProperties": { + "methods": [ + "list_properties" + ] + }, + "ProvisionAccountTicket": { + "methods": [ + "provision_account_ticket" + ] + }, + "RunAccessReport": { + "methods": [ + "run_access_report" + ] + }, + "SearchChangeHistoryEvents": { + "methods": [ + "search_change_history_events" + ] + }, + "UpdateAccount": { + "methods": [ + "update_account" + ] + }, + "UpdateConversionEvent": { + "methods": [ + "update_conversion_event" + ] + }, + "UpdateCustomDimension": { + "methods": [ + "update_custom_dimension" + ] + }, + "UpdateCustomMetric": { + "methods": [ + "update_custom_metric" + ] + }, + "UpdateDataRetentionSettings": { + "methods": [ + "update_data_retention_settings" + ] + }, + "UpdateDataStream": { + "methods": [ + "update_data_stream" + ] + }, + "UpdateGoogleAdsLink": { + "methods": [ + "update_google_ads_link" + ] + }, + "UpdateKeyEvent": { + "methods": [ + "update_key_event" + ] + }, + "UpdateMeasurementProtocolSecret": { + "methods": [ + "update_measurement_protocol_secret" + ] + }, + "UpdateProperty": { + "methods": [ + "update_property" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/gapic_version.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/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-analytics-admin/v1beta/google/analytics/admin_v1beta/py.typed b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/py.typed new file mode 100644 index 000000000000..3b7eb1470672 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-analytics-admin package uses inline types. diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/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-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/__init__.py new file mode 100644 index 000000000000..64d99df43912 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_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 AnalyticsAdminServiceClient +from .async_client import AnalyticsAdminServiceAsyncClient + +__all__ = ( + 'AnalyticsAdminServiceClient', + 'AnalyticsAdminServiceAsyncClient', +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/async_client.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/async_client.py new file mode 100644 index 000000000000..9b74b2669d2b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/async_client.py @@ -0,0 +1,6064 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union +import warnings + +from google.analytics.admin_v1beta 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.analytics.admin_v1beta.services.analytics_admin_service import pagers +from google.analytics.admin_v1beta.types import access_report +from google.analytics.admin_v1beta.types import analytics_admin +from google.analytics.admin_v1beta.types import resources +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 .transports.base import AnalyticsAdminServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AnalyticsAdminServiceGrpcAsyncIOTransport +from .client import AnalyticsAdminServiceClient + + +class AnalyticsAdminServiceAsyncClient: + """Service Interface for the Analytics Admin API (GA4).""" + + _client: AnalyticsAdminServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AnalyticsAdminServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AnalyticsAdminServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + + account_path = staticmethod(AnalyticsAdminServiceClient.account_path) + parse_account_path = staticmethod(AnalyticsAdminServiceClient.parse_account_path) + account_summary_path = staticmethod(AnalyticsAdminServiceClient.account_summary_path) + parse_account_summary_path = staticmethod(AnalyticsAdminServiceClient.parse_account_summary_path) + conversion_event_path = staticmethod(AnalyticsAdminServiceClient.conversion_event_path) + parse_conversion_event_path = staticmethod(AnalyticsAdminServiceClient.parse_conversion_event_path) + custom_dimension_path = staticmethod(AnalyticsAdminServiceClient.custom_dimension_path) + parse_custom_dimension_path = staticmethod(AnalyticsAdminServiceClient.parse_custom_dimension_path) + custom_metric_path = staticmethod(AnalyticsAdminServiceClient.custom_metric_path) + parse_custom_metric_path = staticmethod(AnalyticsAdminServiceClient.parse_custom_metric_path) + data_retention_settings_path = staticmethod(AnalyticsAdminServiceClient.data_retention_settings_path) + parse_data_retention_settings_path = staticmethod(AnalyticsAdminServiceClient.parse_data_retention_settings_path) + data_sharing_settings_path = staticmethod(AnalyticsAdminServiceClient.data_sharing_settings_path) + parse_data_sharing_settings_path = staticmethod(AnalyticsAdminServiceClient.parse_data_sharing_settings_path) + data_stream_path = staticmethod(AnalyticsAdminServiceClient.data_stream_path) + parse_data_stream_path = staticmethod(AnalyticsAdminServiceClient.parse_data_stream_path) + firebase_link_path = staticmethod(AnalyticsAdminServiceClient.firebase_link_path) + parse_firebase_link_path = staticmethod(AnalyticsAdminServiceClient.parse_firebase_link_path) + google_ads_link_path = staticmethod(AnalyticsAdminServiceClient.google_ads_link_path) + parse_google_ads_link_path = staticmethod(AnalyticsAdminServiceClient.parse_google_ads_link_path) + key_event_path = staticmethod(AnalyticsAdminServiceClient.key_event_path) + parse_key_event_path = staticmethod(AnalyticsAdminServiceClient.parse_key_event_path) + measurement_protocol_secret_path = staticmethod(AnalyticsAdminServiceClient.measurement_protocol_secret_path) + parse_measurement_protocol_secret_path = staticmethod(AnalyticsAdminServiceClient.parse_measurement_protocol_secret_path) + organization_path = staticmethod(AnalyticsAdminServiceClient.organization_path) + parse_organization_path = staticmethod(AnalyticsAdminServiceClient.parse_organization_path) + property_path = staticmethod(AnalyticsAdminServiceClient.property_path) + parse_property_path = staticmethod(AnalyticsAdminServiceClient.parse_property_path) + common_billing_account_path = staticmethod(AnalyticsAdminServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AnalyticsAdminServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AnalyticsAdminServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AnalyticsAdminServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AnalyticsAdminServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AnalyticsAdminServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AnalyticsAdminServiceClient.common_project_path) + parse_common_project_path = staticmethod(AnalyticsAdminServiceClient.parse_common_project_path) + common_location_path = staticmethod(AnalyticsAdminServiceClient.common_location_path) + parse_common_location_path = staticmethod(AnalyticsAdminServiceClient.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: + AnalyticsAdminServiceAsyncClient: The constructed client. + """ + return AnalyticsAdminServiceClient.from_service_account_info.__func__(AnalyticsAdminServiceAsyncClient, 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: + AnalyticsAdminServiceAsyncClient: The constructed client. + """ + return AnalyticsAdminServiceClient.from_service_account_file.__func__(AnalyticsAdminServiceAsyncClient, 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 AnalyticsAdminServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AnalyticsAdminServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AnalyticsAdminServiceTransport: 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(AnalyticsAdminServiceClient).get_transport_class, type(AnalyticsAdminServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AnalyticsAdminServiceTransport, Callable[..., AnalyticsAdminServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the analytics admin service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AnalyticsAdminServiceTransport,Callable[..., AnalyticsAdminServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AnalyticsAdminServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AnalyticsAdminServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def get_account(self, + request: Optional[Union[analytics_admin.GetAccountRequest, 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]] = (), + ) -> resources.Account: + r"""Lookup for a single Account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetAccountRequest, dict]]): + The request object. Request message for GetAccount RPC. + name (:class:`str`): + Required. The name of the account to + lookup. Format: accounts/{account} + Example: "accounts/100" + + 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.analytics.admin_v1beta.types.Account: + A resource message representing a + Google Analytics account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAccountRequest): + request = analytics_admin.GetAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_accounts(self, + request: Optional[Union[analytics_admin.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAccountsAsyncPager: + r"""Returns all accounts accessible by the caller. + + Note that these accounts might not currently have GA4 + properties. Soft-deleted (ie: "trashed") accounts are + excluded by default. Returns an empty list if no + relevant accounts are found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_accounts(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListAccountsRequest, dict]]): + The request object. Request message for ListAccounts RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListAccountsAsyncPager: + Request message for ListAccounts RPC. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccountsRequest): + request = analytics_admin.ListAccountsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_accounts] + + # 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.ListAccountsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_account(self, + request: Optional[Union[analytics_admin.DeleteAccountRequest, 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"""Marks target Account as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + accounts. However, they can be restored using the Trash + Can UI. + + If the accounts are not restored before the expiration + time, the account and all child resources (eg: + Properties, GoogleAdsLinks, Streams, AccessBindings) + will be permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_delete_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + await client.delete_account(request=request) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.DeleteAccountRequest, dict]]): + The request object. Request message for DeleteAccount + RPC. + name (:class:`str`): + Required. The name of the Account to + soft-delete. Format: accounts/{account} + Example: "accounts/100" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAccountRequest): + request = analytics_admin.DeleteAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_account] + + # Certain fields should be provided within 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 update_account(self, + request: Optional[Union[analytics_admin.UpdateAccountRequest, dict]] = None, + *, + account: Optional[resources.Account] = 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]] = (), + ) -> resources.Account: + r"""Updates an account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + account = admin_v1beta.Account() + account.display_name = "display_name_value" + + request = admin_v1beta.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = await client.update_account(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdateAccountRequest, dict]]): + The request object. Request message for UpdateAccount + RPC. + account (:class:`google.analytics.admin_v1beta.types.Account`): + Required. The account to update. The account's ``name`` + field is used to identify the account. + + This corresponds to the ``account`` 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 list of fields to be updated. Field names + must be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "*" to match + all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.Account: + A resource message representing a + Google Analytics account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([account, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAccountRequest): + request = analytics_admin.UpdateAccountRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account is not None: + request.account = account + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account.name", request.account.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 provision_account_ticket(self, + request: Optional[Union[analytics_admin.ProvisionAccountTicketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ProvisionAccountTicketResponse: + r"""Requests a ticket for creating an account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_provision_account_ticket(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ProvisionAccountTicketRequest( + ) + + # Make the request + response = await client.provision_account_ticket(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ProvisionAccountTicketRequest, dict]]): + The request object. Request message for + ProvisionAccountTicket RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.ProvisionAccountTicketResponse: + Response message for + ProvisionAccountTicket RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ProvisionAccountTicketRequest): + request = analytics_admin.ProvisionAccountTicketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.provision_account_ticket] + + # 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_account_summaries(self, + request: Optional[Union[analytics_admin.ListAccountSummariesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAccountSummariesAsyncPager: + r"""Returns summaries of all accounts accessible by the + caller. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_account_summaries(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListAccountSummariesRequest( + ) + + # Make the request + page_result = client.list_account_summaries(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListAccountSummariesRequest, dict]]): + The request object. Request message for + ListAccountSummaries RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListAccountSummariesAsyncPager: + Response message for + ListAccountSummaries RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccountSummariesRequest): + request = analytics_admin.ListAccountSummariesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_account_summaries] + + # 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.ListAccountSummariesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_property(self, + request: Optional[Union[analytics_admin.GetPropertyRequest, 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]] = (), + ) -> resources.Property: + r"""Lookup for a single "GA4" Property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetPropertyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_property(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetPropertyRequest, dict]]): + The request object. Request message for GetProperty RPC. + name (:class:`str`): + Required. The name of the property to lookup. Format: + properties/{property_id} Example: "properties/1000" + + 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.analytics.admin_v1beta.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetPropertyRequest): + request = analytics_admin.GetPropertyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_property] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_properties(self, + request: Optional[Union[analytics_admin.ListPropertiesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPropertiesAsyncPager: + r"""Returns child Properties under the specified parent + Account. + Only "GA4" properties will be returned. + Properties will be excluded if the caller does not have + access. Soft-deleted (ie: "trashed") properties are + excluded by default. Returns an empty list if no + relevant properties are found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_properties(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListPropertiesRequest( + filter="filter_value", + ) + + # Make the request + page_result = client.list_properties(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListPropertiesRequest, dict]]): + The request object. Request message for ListProperties + RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListPropertiesAsyncPager: + Response message for ListProperties + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListPropertiesRequest): + request = analytics_admin.ListPropertiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_properties] + + # 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.ListPropertiesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_property(self, + request: Optional[Union[analytics_admin.CreatePropertyRequest, dict]] = None, + *, + property: Optional[resources.Property] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Property: + r"""Creates an "GA4" property with the specified location + and attributes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_create_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + property = admin_v1beta.Property() + property.display_name = "display_name_value" + property.time_zone = "time_zone_value" + + request = admin_v1beta.CreatePropertyRequest( + property=property, + ) + + # Make the request + response = await client.create_property(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.CreatePropertyRequest, dict]]): + The request object. Request message for CreateProperty + RPC. + property (:class:`google.analytics.admin_v1beta.types.Property`): + Required. The property to create. + Note: the supplied property must specify + its parent. + + This corresponds to the ``property`` 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.analytics.admin_v1beta.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([property]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreatePropertyRequest): + request = analytics_admin.CreatePropertyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if property is not None: + request.property = property + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_property] + + # 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_property(self, + request: Optional[Union[analytics_admin.DeletePropertyRequest, 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]] = (), + ) -> resources.Property: + r"""Marks target Property as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + properties. However, they can be restored using the + Trash Can UI. + + If the properties are not restored before the expiration + time, the Property and all child resources (eg: + GoogleAdsLinks, Streams, AccessBindings) will be + permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found, or is not a + GA4 Property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_delete_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeletePropertyRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_property(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.DeletePropertyRequest, dict]]): + The request object. Request message for DeleteProperty + RPC. + name (:class:`str`): + Required. The name of the Property to soft-delete. + Format: properties/{property_id} Example: + "properties/1000" + + 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.analytics.admin_v1beta.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeletePropertyRequest): + request = analytics_admin.DeletePropertyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_property] + + # Certain fields should be provided within 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_property(self, + request: Optional[Union[analytics_admin.UpdatePropertyRequest, dict]] = None, + *, + property: Optional[resources.Property] = 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]] = (), + ) -> resources.Property: + r"""Updates a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + property = admin_v1beta.Property() + property.display_name = "display_name_value" + property.time_zone = "time_zone_value" + + request = admin_v1beta.UpdatePropertyRequest( + property=property, + ) + + # Make the request + response = await client.update_property(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdatePropertyRequest, dict]]): + The request object. Request message for UpdateProperty + RPC. + property (:class:`google.analytics.admin_v1beta.types.Property`): + Required. The property to update. The property's + ``name`` field is used to identify the property to be + updated. + + This corresponds to the ``property`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([property, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdatePropertyRequest): + request = analytics_admin.UpdatePropertyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if property is not None: + request.property = property + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_property] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property.name", request.property.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_firebase_link(self, + request: Optional[Union[analytics_admin.CreateFirebaseLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + firebase_link: Optional[resources.FirebaseLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.FirebaseLink: + r"""Creates a FirebaseLink. + + Properties can have at most one FirebaseLink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_create_firebase_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateFirebaseLinkRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_firebase_link(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.CreateFirebaseLinkRequest, dict]]): + The request object. Request message for + CreateFirebaseLink RPC + parent (:class:`str`): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firebase_link (:class:`google.analytics.admin_v1beta.types.FirebaseLink`): + Required. The Firebase link to + create. + + This corresponds to the ``firebase_link`` 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.analytics.admin_v1beta.types.FirebaseLink: + A link between a GA4 property and a + Firebase project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, firebase_link]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateFirebaseLinkRequest): + request = analytics_admin.CreateFirebaseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if firebase_link is not None: + request.firebase_link = firebase_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_firebase_link] + + # Certain 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 delete_firebase_link(self, + request: Optional[Union[analytics_admin.DeleteFirebaseLinkRequest, 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 FirebaseLink on a property + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_delete_firebase_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteFirebaseLinkRequest( + name="name_value", + ) + + # Make the request + await client.delete_firebase_link(request=request) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.DeleteFirebaseLinkRequest, dict]]): + The request object. Request message for + DeleteFirebaseLink RPC + name (:class:`str`): + Required. Format: + properties/{property_id}/firebaseLinks/{firebase_link_id} + + Example: ``properties/1234/firebaseLinks/5678`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteFirebaseLinkRequest): + request = analytics_admin.DeleteFirebaseLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_firebase_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_firebase_links(self, + request: Optional[Union[analytics_admin.ListFirebaseLinksRequest, 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.ListFirebaseLinksAsyncPager: + r"""Lists FirebaseLinks on a property. + Properties can have at most one FirebaseLink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_firebase_links(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListFirebaseLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_firebase_links(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListFirebaseLinksRequest, dict]]): + The request object. Request message for ListFirebaseLinks + RPC + parent (:class:`str`): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListFirebaseLinksAsyncPager: + Response message for + ListFirebaseLinks RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListFirebaseLinksRequest): + request = analytics_admin.ListFirebaseLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_firebase_links] + + # Certain 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.ListFirebaseLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_google_ads_link(self, + request: Optional[Union[analytics_admin.CreateGoogleAdsLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_ads_link: Optional[resources.GoogleAdsLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.GoogleAdsLink: + r"""Creates a GoogleAdsLink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_create_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateGoogleAdsLinkRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_google_ads_link(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.CreateGoogleAdsLinkRequest, dict]]): + The request object. Request message for + CreateGoogleAdsLink RPC + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_ads_link (:class:`google.analytics.admin_v1beta.types.GoogleAdsLink`): + Required. The GoogleAdsLink to + create. + + This corresponds to the ``google_ads_link`` 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.analytics.admin_v1beta.types.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, google_ads_link]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateGoogleAdsLinkRequest): + request = analytics_admin.CreateGoogleAdsLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if google_ads_link is not None: + request.google_ads_link = google_ads_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_google_ads_link] + + # Certain 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_google_ads_link(self, + request: Optional[Union[analytics_admin.UpdateGoogleAdsLinkRequest, dict]] = None, + *, + google_ads_link: Optional[resources.GoogleAdsLink] = 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]] = (), + ) -> resources.GoogleAdsLink: + r"""Updates a GoogleAdsLink on a property + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateGoogleAdsLinkRequest( + ) + + # Make the request + response = await client.update_google_ads_link(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdateGoogleAdsLinkRequest, dict]]): + The request object. Request message for + UpdateGoogleAdsLink RPC + google_ads_link (:class:`google.analytics.admin_v1beta.types.GoogleAdsLink`): + The GoogleAdsLink to update + This corresponds to the ``google_ads_link`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_ads_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateGoogleAdsLinkRequest): + request = analytics_admin.UpdateGoogleAdsLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_ads_link is not None: + request.google_ads_link = google_ads_link + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_google_ads_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_ads_link.name", request.google_ads_link.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_google_ads_link(self, + request: Optional[Union[analytics_admin.DeleteGoogleAdsLinkRequest, 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 GoogleAdsLink on a property + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_delete_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteGoogleAdsLinkRequest( + name="name_value", + ) + + # Make the request + await client.delete_google_ads_link(request=request) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.DeleteGoogleAdsLinkRequest, dict]]): + The request object. Request message for + DeleteGoogleAdsLink RPC. + name (:class:`str`): + Required. Example format: + properties/1234/googleAdsLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteGoogleAdsLinkRequest): + request = analytics_admin.DeleteGoogleAdsLinkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_google_ads_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_google_ads_links(self, + request: Optional[Union[analytics_admin.ListGoogleAdsLinksRequest, 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.ListGoogleAdsLinksAsyncPager: + r"""Lists GoogleAdsLinks on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_google_ads_links(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListGoogleAdsLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_ads_links(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListGoogleAdsLinksRequest, dict]]): + The request object. Request message for + ListGoogleAdsLinks RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListGoogleAdsLinksAsyncPager: + Response message for + ListGoogleAdsLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListGoogleAdsLinksRequest): + request = analytics_admin.ListGoogleAdsLinksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_google_ads_links] + + # Certain 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.ListGoogleAdsLinksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_data_sharing_settings(self, + request: Optional[Union[analytics_admin.GetDataSharingSettingsRequest, 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]] = (), + ) -> resources.DataSharingSettings: + r"""Get data sharing settings on an account. + Data sharing settings are singletons. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_data_sharing_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataSharingSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_sharing_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetDataSharingSettingsRequest, dict]]): + The request object. Request message for + GetDataSharingSettings RPC. + name (:class:`str`): + Required. The name of the settings to lookup. Format: + accounts/{account}/dataSharingSettings + + Example: ``accounts/1000/dataSharingSettings`` + + 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.analytics.admin_v1beta.types.DataSharingSettings: + A resource message representing data + sharing settings of a Google Analytics + account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataSharingSettingsRequest): + request = analytics_admin.GetDataSharingSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_data_sharing_settings] + + # Certain fields should be provided within 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_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.GetMeasurementProtocolSecretRequest, 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]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Lookup for a single "GA4" MeasurementProtocolSecret. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetMeasurementProtocolSecretRequest( + name="name_value", + ) + + # Make the request + response = await client.get_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetMeasurementProtocolSecretRequest, dict]]): + The request object. Request message for + GetMeasurementProtocolSecret RPC. + name (:class:`str`): + Required. The name of the measurement + protocol secret to lookup. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + + 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.analytics.admin_v1beta.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetMeasurementProtocolSecretRequest): + request = analytics_admin.GetMeasurementProtocolSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_measurement_protocol_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_measurement_protocol_secrets(self, + request: Optional[Union[analytics_admin.ListMeasurementProtocolSecretsRequest, 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.ListMeasurementProtocolSecretsAsyncPager: + r"""Returns child MeasurementProtocolSecrets under the + specified parent Property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_measurement_protocol_secrets(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListMeasurementProtocolSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_measurement_protocol_secrets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsRequest, dict]]): + The request object. Request message for + ListMeasurementProtocolSecret RPC + parent (:class:`str`): + Required. The resource name of the + parent stream. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListMeasurementProtocolSecretsAsyncPager: + Response message for + ListMeasurementProtocolSecret RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListMeasurementProtocolSecretsRequest): + request = analytics_admin.ListMeasurementProtocolSecretsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_measurement_protocol_secrets] + + # Certain 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.ListMeasurementProtocolSecretsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.CreateMeasurementProtocolSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + measurement_protocol_secret: Optional[resources.MeasurementProtocolSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Creates a measurement protocol secret. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_create_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + measurement_protocol_secret = admin_v1beta.MeasurementProtocolSecret() + measurement_protocol_secret.display_name = "display_name_value" + + request = admin_v1beta.CreateMeasurementProtocolSecretRequest( + parent="parent_value", + measurement_protocol_secret=measurement_protocol_secret, + ) + + # Make the request + response = await client.create_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.CreateMeasurementProtocolSecretRequest, dict]]): + The request object. Request message for + CreateMeasurementProtocolSecret RPC + parent (:class:`str`): + Required. The parent resource where + this secret will be created. Format: + properties/{property}/dataStreams/{dataStream} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + measurement_protocol_secret (:class:`google.analytics.admin_v1beta.types.MeasurementProtocolSecret`): + Required. The measurement protocol + secret to create. + + This corresponds to the ``measurement_protocol_secret`` 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.analytics.admin_v1beta.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, measurement_protocol_secret]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateMeasurementProtocolSecretRequest): + request = analytics_admin.CreateMeasurementProtocolSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if measurement_protocol_secret is not None: + request.measurement_protocol_secret = measurement_protocol_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_measurement_protocol_secret] + + # Certain 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 delete_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.DeleteMeasurementProtocolSecretRequest, 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 target MeasurementProtocolSecret. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_delete_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteMeasurementProtocolSecretRequest( + name="name_value", + ) + + # Make the request + await client.delete_measurement_protocol_secret(request=request) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.DeleteMeasurementProtocolSecretRequest, dict]]): + The request object. Request message for + DeleteMeasurementProtocolSecret RPC + name (:class:`str`): + Required. The name of the + MeasurementProtocolSecret to delete. + Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteMeasurementProtocolSecretRequest): + request = analytics_admin.DeleteMeasurementProtocolSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_measurement_protocol_secret] + + # Certain fields should be provided within 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 update_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.UpdateMeasurementProtocolSecretRequest, dict]] = None, + *, + measurement_protocol_secret: Optional[resources.MeasurementProtocolSecret] = 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]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Updates a measurement protocol secret. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + measurement_protocol_secret = admin_v1beta.MeasurementProtocolSecret() + measurement_protocol_secret.display_name = "display_name_value" + + request = admin_v1beta.UpdateMeasurementProtocolSecretRequest( + measurement_protocol_secret=measurement_protocol_secret, + ) + + # Make the request + response = await client.update_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdateMeasurementProtocolSecretRequest, dict]]): + The request object. Request message for + UpdateMeasurementProtocolSecret RPC + measurement_protocol_secret (:class:`google.analytics.admin_v1beta.types.MeasurementProtocolSecret`): + Required. The measurement protocol + secret to update. + + This corresponds to the ``measurement_protocol_secret`` 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 list of fields to be + updated. Omitted fields will not be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([measurement_protocol_secret, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateMeasurementProtocolSecretRequest): + request = analytics_admin.UpdateMeasurementProtocolSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if measurement_protocol_secret is not None: + request.measurement_protocol_secret = measurement_protocol_secret + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_measurement_protocol_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("measurement_protocol_secret.name", request.measurement_protocol_secret.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 acknowledge_user_data_collection(self, + request: Optional[Union[analytics_admin.AcknowledgeUserDataCollectionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.AcknowledgeUserDataCollectionResponse: + r"""Acknowledges the terms of user data collection for + the specified property. + This acknowledgement must be completed (either in the + Google Analytics UI or through this API) before + MeasurementProtocolSecret resources may be created. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_acknowledge_user_data_collection(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.AcknowledgeUserDataCollectionRequest( + property="property_value", + acknowledgement="acknowledgement_value", + ) + + # Make the request + response = await client.acknowledge_user_data_collection(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.AcknowledgeUserDataCollectionRequest, dict]]): + The request object. Request message for + AcknowledgeUserDataCollection RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.AcknowledgeUserDataCollectionResponse: + Response message for + AcknowledgeUserDataCollection RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.AcknowledgeUserDataCollectionRequest): + request = analytics_admin.AcknowledgeUserDataCollectionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.acknowledge_user_data_collection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # 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 search_change_history_events(self, + request: Optional[Union[analytics_admin.SearchChangeHistoryEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchChangeHistoryEventsAsyncPager: + r"""Searches through all changes to an account or its + children given the specified set of filters. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_search_change_history_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.SearchChangeHistoryEventsRequest( + account="account_value", + ) + + # Make the request + page_result = client.search_change_history_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.SearchChangeHistoryEventsRequest, dict]]): + The request object. Request message for + SearchChangeHistoryEvents RPC. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.services.analytics_admin_service.pagers.SearchChangeHistoryEventsAsyncPager: + Response message for SearchAccounts + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.SearchChangeHistoryEventsRequest): + request = analytics_admin.SearchChangeHistoryEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.search_change_history_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account", request.account), + )), + ) + + # 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.SearchChangeHistoryEventsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_conversion_event(self, + request: Optional[Union[analytics_admin.CreateConversionEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversion_event: Optional[resources.ConversionEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_create_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateConversionEventRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_conversion_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.CreateConversionEventRequest, dict]]): + The request object. Request message for + CreateConversionEvent RPC + parent (:class:`str`): + Required. The resource name of the + parent property where this conversion + event will be created. Format: + properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversion_event (:class:`google.analytics.admin_v1beta.types.ConversionEvent`): + Required. The conversion event to + create. + + This corresponds to the ``conversion_event`` 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.analytics.admin_v1beta.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.create_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversion_event]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateConversionEventRequest): + request = analytics_admin.CreateConversionEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversion_event is not None: + request.conversion_event = conversion_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_conversion_event(self, + request: Optional[Union[analytics_admin.UpdateConversionEventRequest, dict]] = None, + *, + conversion_event: Optional[resources.ConversionEvent] = 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]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateConversionEventRequest( + ) + + # Make the request + response = await client.update_conversion_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdateConversionEventRequest, dict]]): + The request object. Request message for + UpdateConversionEvent RPC + conversion_event (:class:`google.analytics.admin_v1beta.types.ConversionEvent`): + Required. The conversion event to update. The ``name`` + field is used to identify the settings to be updated. + + This corresponds to the ``conversion_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.update_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversion_event, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateConversionEventRequest): + request = analytics_admin.UpdateConversionEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversion_event is not None: + request.conversion_event = conversion_event + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversion_event.name", request.conversion_event.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_conversion_event(self, + request: Optional[Union[analytics_admin.GetConversionEventRequest, 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]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetConversionEventRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversion_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetConversionEventRequest, dict]]): + The request object. Request message for + GetConversionEvent RPC + name (:class:`str`): + Required. The resource name of the conversion event to + retrieve. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456" + + 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.analytics.admin_v1beta.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.get_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetConversionEventRequest): + request = analytics_admin.GetConversionEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_conversion_event(self, + request: Optional[Union[analytics_admin.DeleteConversionEventRequest, 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"""Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_delete_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteConversionEventRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversion_event(request=request) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.DeleteConversionEventRequest, dict]]): + The request object. Request message for + DeleteConversionEvent RPC + name (:class:`str`): + Required. The resource name of the conversion event to + delete. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456" + + 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. + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.delete_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteConversionEventRequest): + request = analytics_admin.DeleteConversionEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_conversion_events(self, + request: Optional[Union[analytics_admin.ListConversionEventsRequest, 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.ListConversionEventsAsyncPager: + r"""Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + + Returns an empty list if no conversion events are found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_conversion_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListConversionEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversion_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListConversionEventsRequest, dict]]): + The request object. Request message for + ListConversionEvents RPC + parent (:class:`str`): + Required. The resource name of the + parent property. Example: + 'properties/123' + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListConversionEventsAsyncPager: + Response message for + ListConversionEvents RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("AnalyticsAdminServiceAsyncClient.list_conversion_events is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListConversionEventsRequest): + request = analytics_admin.ListConversionEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_conversion_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversionEventsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_key_event(self, + request: Optional[Union[analytics_admin.CreateKeyEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + key_event: Optional[resources.KeyEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyEvent: + r"""Creates a Key Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_create_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + key_event = admin_v1beta.KeyEvent() + key_event.counting_method = "ONCE_PER_SESSION" + + request = admin_v1beta.CreateKeyEventRequest( + key_event=key_event, + parent="parent_value", + ) + + # Make the request + response = await client.create_key_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.CreateKeyEventRequest, dict]]): + The request object. Request message for CreateKeyEvent + RPC + parent (:class:`str`): + Required. The resource name of the + parent property where this Key Event + will be created. Format: properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_event (:class:`google.analytics.admin_v1beta.types.KeyEvent`): + Required. The Key Event to create. + This corresponds to the ``key_event`` 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.analytics.admin_v1beta.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, key_event]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateKeyEventRequest): + request = analytics_admin.CreateKeyEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_event is not None: + request.key_event = key_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_key_event(self, + request: Optional[Union[analytics_admin.UpdateKeyEventRequest, dict]] = None, + *, + key_event: Optional[resources.KeyEvent] = 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]] = (), + ) -> resources.KeyEvent: + r"""Updates a Key Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + key_event = admin_v1beta.KeyEvent() + key_event.counting_method = "ONCE_PER_SESSION" + + request = admin_v1beta.UpdateKeyEventRequest( + key_event=key_event, + ) + + # Make the request + response = await client.update_key_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdateKeyEventRequest, dict]]): + The request object. Request message for UpdateKeyEvent + RPC + key_event (:class:`google.analytics.admin_v1beta.types.KeyEvent`): + Required. The Key Event to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``key_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([key_event, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateKeyEventRequest): + request = analytics_admin.UpdateKeyEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if key_event is not None: + request.key_event = key_event + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("key_event.name", request.key_event.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_key_event(self, + request: Optional[Union[analytics_admin.GetKeyEventRequest, 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]] = (), + ) -> resources.KeyEvent: + r"""Retrieve a single Key Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetKeyEventRequest( + name="name_value", + ) + + # Make the request + response = await client.get_key_event(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetKeyEventRequest, dict]]): + The request object. Request message for GetKeyEvent RPC + name (:class:`str`): + Required. The resource name of the Key Event to + retrieve. Format: + properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456" + + 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.analytics.admin_v1beta.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetKeyEventRequest): + request = analytics_admin.GetKeyEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_key_event(self, + request: Optional[Union[analytics_admin.DeleteKeyEventRequest, 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 Key Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_delete_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteKeyEventRequest( + name="name_value", + ) + + # Make the request + await client.delete_key_event(request=request) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.DeleteKeyEventRequest, dict]]): + The request object. Request message for DeleteKeyEvent + RPC + name (:class:`str`): + Required. The resource name of the Key Event to delete. + Format: properties/{property}/keyEvents/{key_event} + Example: "properties/123/keyEvents/456" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteKeyEventRequest): + request = analytics_admin.DeleteKeyEventRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_key_events(self, + request: Optional[Union[analytics_admin.ListKeyEventsRequest, 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.ListKeyEventsAsyncPager: + r"""Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_key_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListKeyEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListKeyEventsRequest, dict]]): + The request object. Request message for ListKeyEvents RPC + parent (:class:`str`): + Required. The resource name of the + parent property. Example: + 'properties/123' + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListKeyEventsAsyncPager: + Response message for ListKeyEvents + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListKeyEventsRequest): + request = analytics_admin.ListKeyEventsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_key_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListKeyEventsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_custom_dimension(self, + request: Optional[Union[analytics_admin.CreateCustomDimensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_dimension: Optional[resources.CustomDimension] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CustomDimension: + r"""Creates a CustomDimension. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_create_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + custom_dimension = admin_v1beta.CustomDimension() + custom_dimension.parameter_name = "parameter_name_value" + custom_dimension.display_name = "display_name_value" + custom_dimension.scope = "ITEM" + + request = admin_v1beta.CreateCustomDimensionRequest( + parent="parent_value", + custom_dimension=custom_dimension, + ) + + # Make the request + response = await client.create_custom_dimension(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.CreateCustomDimensionRequest, dict]]): + The request object. Request message for + CreateCustomDimension RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_dimension (:class:`google.analytics.admin_v1beta.types.CustomDimension`): + Required. The CustomDimension to + create. + + This corresponds to the ``custom_dimension`` 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.analytics.admin_v1beta.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_dimension]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCustomDimensionRequest): + request = analytics_admin.CreateCustomDimensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_dimension is not None: + request.custom_dimension = custom_dimension + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_custom_dimension] + + # Certain 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_custom_dimension(self, + request: Optional[Union[analytics_admin.UpdateCustomDimensionRequest, dict]] = None, + *, + custom_dimension: Optional[resources.CustomDimension] = 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]] = (), + ) -> resources.CustomDimension: + r"""Updates a CustomDimension on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateCustomDimensionRequest( + ) + + # Make the request + response = await client.update_custom_dimension(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdateCustomDimensionRequest, dict]]): + The request object. Request message for + UpdateCustomDimension RPC. + custom_dimension (:class:`google.analytics.admin_v1beta.types.CustomDimension`): + The CustomDimension to update + This corresponds to the ``custom_dimension`` 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 list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_dimension, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCustomDimensionRequest): + request = analytics_admin.UpdateCustomDimensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_dimension is not None: + request.custom_dimension = custom_dimension + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_custom_dimension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("custom_dimension.name", request.custom_dimension.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_custom_dimensions(self, + request: Optional[Union[analytics_admin.ListCustomDimensionsRequest, 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.ListCustomDimensionsAsyncPager: + r"""Lists CustomDimensions on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_custom_dimensions(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListCustomDimensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_dimensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListCustomDimensionsRequest, dict]]): + The request object. Request message for + ListCustomDimensions RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListCustomDimensionsAsyncPager: + Response message for + ListCustomDimensions RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCustomDimensionsRequest): + request = analytics_admin.ListCustomDimensionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_custom_dimensions] + + # Certain 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.ListCustomDimensionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def archive_custom_dimension(self, + request: Optional[Union[analytics_admin.ArchiveCustomDimensionRequest, 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"""Archives a CustomDimension on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_archive_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ArchiveCustomDimensionRequest( + name="name_value", + ) + + # Make the request + await client.archive_custom_dimension(request=request) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ArchiveCustomDimensionRequest, dict]]): + The request object. Request message for + ArchiveCustomDimension RPC. + name (:class:`str`): + Required. The name of the + CustomDimension to archive. Example + format: + properties/1234/customDimensions/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveCustomDimensionRequest): + request = analytics_admin.ArchiveCustomDimensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.archive_custom_dimension] + + # Certain fields should be provided within 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_custom_dimension(self, + request: Optional[Union[analytics_admin.GetCustomDimensionRequest, 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]] = (), + ) -> resources.CustomDimension: + r"""Lookup for a single CustomDimension. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetCustomDimensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_custom_dimension(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetCustomDimensionRequest, dict]]): + The request object. Request message for + GetCustomDimension RPC. + name (:class:`str`): + Required. The name of the + CustomDimension to get. Example format: + properties/1234/customDimensions/5678 + + 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.analytics.admin_v1beta.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCustomDimensionRequest): + request = analytics_admin.GetCustomDimensionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_custom_dimension] + + # Certain fields should be provided within 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_custom_metric(self, + request: Optional[Union[analytics_admin.CreateCustomMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_metric: Optional[resources.CustomMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CustomMetric: + r"""Creates a CustomMetric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_create_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + custom_metric = admin_v1beta.CustomMetric() + custom_metric.parameter_name = "parameter_name_value" + custom_metric.display_name = "display_name_value" + custom_metric.measurement_unit = "HOURS" + custom_metric.scope = "EVENT" + + request = admin_v1beta.CreateCustomMetricRequest( + parent="parent_value", + custom_metric=custom_metric, + ) + + # Make the request + response = await client.create_custom_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.CreateCustomMetricRequest, dict]]): + The request object. Request message for + CreateCustomMetric RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_metric (:class:`google.analytics.admin_v1beta.types.CustomMetric`): + Required. The CustomMetric to create. + This corresponds to the ``custom_metric`` 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.analytics.admin_v1beta.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_metric]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCustomMetricRequest): + request = analytics_admin.CreateCustomMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_metric is not None: + request.custom_metric = custom_metric + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_custom_metric] + + # Certain 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_custom_metric(self, + request: Optional[Union[analytics_admin.UpdateCustomMetricRequest, dict]] = None, + *, + custom_metric: Optional[resources.CustomMetric] = 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]] = (), + ) -> resources.CustomMetric: + r"""Updates a CustomMetric on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateCustomMetricRequest( + ) + + # Make the request + response = await client.update_custom_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdateCustomMetricRequest, dict]]): + The request object. Request message for + UpdateCustomMetric RPC. + custom_metric (:class:`google.analytics.admin_v1beta.types.CustomMetric`): + The CustomMetric to update + This corresponds to the ``custom_metric`` 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 list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_metric, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCustomMetricRequest): + request = analytics_admin.UpdateCustomMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_metric is not None: + request.custom_metric = custom_metric + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_custom_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("custom_metric.name", request.custom_metric.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_custom_metrics(self, + request: Optional[Union[analytics_admin.ListCustomMetricsRequest, 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.ListCustomMetricsAsyncPager: + r"""Lists CustomMetrics on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_custom_metrics(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListCustomMetricsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_metrics(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListCustomMetricsRequest, dict]]): + The request object. Request message for ListCustomMetrics + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListCustomMetricsAsyncPager: + Response message for + ListCustomMetrics RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCustomMetricsRequest): + request = analytics_admin.ListCustomMetricsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_custom_metrics] + + # Certain 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.ListCustomMetricsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def archive_custom_metric(self, + request: Optional[Union[analytics_admin.ArchiveCustomMetricRequest, 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"""Archives a CustomMetric on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_archive_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ArchiveCustomMetricRequest( + name="name_value", + ) + + # Make the request + await client.archive_custom_metric(request=request) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ArchiveCustomMetricRequest, dict]]): + The request object. Request message for + ArchiveCustomMetric RPC. + name (:class:`str`): + Required. The name of the + CustomMetric to archive. Example format: + properties/1234/customMetrics/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveCustomMetricRequest): + request = analytics_admin.ArchiveCustomMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.archive_custom_metric] + + # Certain fields should be provided within 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_custom_metric(self, + request: Optional[Union[analytics_admin.GetCustomMetricRequest, 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]] = (), + ) -> resources.CustomMetric: + r"""Lookup for a single CustomMetric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetCustomMetricRequest( + name="name_value", + ) + + # Make the request + response = await client.get_custom_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetCustomMetricRequest, dict]]): + The request object. Request message for GetCustomMetric + RPC. + name (:class:`str`): + Required. The name of the + CustomMetric to get. Example format: + properties/1234/customMetrics/5678 + + 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.analytics.admin_v1beta.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCustomMetricRequest): + request = analytics_admin.GetCustomMetricRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_custom_metric] + + # Certain fields should be provided within 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_data_retention_settings(self, + request: Optional[Union[analytics_admin.GetDataRetentionSettingsRequest, 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]] = (), + ) -> resources.DataRetentionSettings: + r"""Returns the singleton data retention settings for + this property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_data_retention_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataRetentionSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_retention_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetDataRetentionSettingsRequest, dict]]): + The request object. Request message for + GetDataRetentionSettings RPC. + name (:class:`str`): + Required. The name of the settings to + lookup. Format: + + properties/{property}/dataRetentionSettings + Example: + "properties/1000/dataRetentionSettings" + + 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.analytics.admin_v1beta.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataRetentionSettingsRequest): + request = analytics_admin.GetDataRetentionSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_data_retention_settings] + + # Certain fields should be provided within 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_data_retention_settings(self, + request: Optional[Union[analytics_admin.UpdateDataRetentionSettingsRequest, dict]] = None, + *, + data_retention_settings: Optional[resources.DataRetentionSettings] = 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]] = (), + ) -> resources.DataRetentionSettings: + r"""Updates the singleton data retention settings for + this property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_data_retention_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateDataRetentionSettingsRequest( + ) + + # Make the request + response = await client.update_data_retention_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdateDataRetentionSettingsRequest, dict]]): + The request object. Request message for + UpdateDataRetentionSettings RPC. + data_retention_settings (:class:`google.analytics.admin_v1beta.types.DataRetentionSettings`): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``data_retention_settings`` 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 list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_retention_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataRetentionSettingsRequest): + request = analytics_admin.UpdateDataRetentionSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_retention_settings is not None: + request.data_retention_settings = data_retention_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_data_retention_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_retention_settings.name", request.data_retention_settings.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_data_stream(self, + request: Optional[Union[analytics_admin.CreateDataStreamRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_stream: Optional[resources.DataStream] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DataStream: + r"""Creates a DataStream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_create_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + data_stream = admin_v1beta.DataStream() + data_stream.type_ = "IOS_APP_DATA_STREAM" + + request = admin_v1beta.CreateDataStreamRequest( + parent="parent_value", + data_stream=data_stream, + ) + + # Make the request + response = await client.create_data_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.CreateDataStreamRequest, dict]]): + The request object. Request message for CreateDataStream + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_stream (:class:`google.analytics.admin_v1beta.types.DataStream`): + Required. The DataStream to create. + This corresponds to the ``data_stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_stream]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateDataStreamRequest): + request = analytics_admin.CreateDataStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_stream is not None: + request.data_stream = data_stream + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_data_stream(self, + request: Optional[Union[analytics_admin.DeleteDataStreamRequest, 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 DataStream on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_delete_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteDataStreamRequest( + name="name_value", + ) + + # Make the request + await client.delete_data_stream(request=request) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.DeleteDataStreamRequest, dict]]): + The request object. Request message for DeleteDataStream + RPC. + name (:class:`str`): + Required. The name of the DataStream + to delete. Example format: + properties/1234/dataStreams/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteDataStreamRequest): + request = analytics_admin.DeleteDataStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.delete_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_data_stream(self, + request: Optional[Union[analytics_admin.UpdateDataStreamRequest, dict]] = None, + *, + data_stream: Optional[resources.DataStream] = 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]] = (), + ) -> resources.DataStream: + r"""Updates a DataStream on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_update_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateDataStreamRequest( + ) + + # Make the request + response = await client.update_data_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.UpdateDataStreamRequest, dict]]): + The request object. Request message for UpdateDataStream + RPC. + data_stream (:class:`google.analytics.admin_v1beta.types.DataStream`): + The DataStream to update + This corresponds to the ``data_stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_stream, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataStreamRequest): + request = analytics_admin.UpdateDataStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_stream is not None: + request.data_stream = data_stream + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_stream.name", request.data_stream.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_data_streams(self, + request: Optional[Union[analytics_admin.ListDataStreamsRequest, 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.ListDataStreamsAsyncPager: + r"""Lists DataStreams on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_list_data_streams(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListDataStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_streams(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.ListDataStreamsRequest, dict]]): + The request object. Request message for ListDataStreams + RPC. + parent (:class:`str`): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListDataStreamsAsyncPager: + Response message for ListDataStreams + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListDataStreamsRequest): + request = analytics_admin.ListDataStreamsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_data_streams] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDataStreamsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_data_stream(self, + request: Optional[Union[analytics_admin.GetDataStreamRequest, 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]] = (), + ) -> resources.DataStream: + r"""Lookup for a single DataStream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_get_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataStreamRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.GetDataStreamRequest, dict]]): + The request object. Request message for GetDataStream + RPC. + name (:class:`str`): + Required. The name of the DataStream + to get. Example format: + properties/1234/dataStreams/5678 + + 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.analytics.admin_v1beta.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataStreamRequest): + request = analytics_admin.GetDataStreamRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_access_report(self, + request: Optional[Union[analytics_admin.RunAccessReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.RunAccessReportResponse: + r"""Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. + + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + async def sample_run_access_report(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.RunAccessReportRequest( + ) + + # Make the request + response = await client.run_access_report(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.analytics.admin_v1beta.types.RunAccessReportRequest, dict]]): + The request object. The request for a Data Access Record + Report. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.RunAccessReportResponse: + The customized Data Access Record + Report response. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.RunAccessReportRequest): + request = analytics_admin.RunAccessReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.run_access_report] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity", request.entity), + )), + ) + + # 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) -> "AnalyticsAdminServiceAsyncClient": + 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__ = ( + "AnalyticsAdminServiceAsyncClient", +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/client.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/client.py new file mode 100644 index 000000000000..9aaa3fd19687 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/client.py @@ -0,0 +1,6489 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.analytics.admin_v1beta 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.analytics.admin_v1beta.services.analytics_admin_service import pagers +from google.analytics.admin_v1beta.types import access_report +from google.analytics.admin_v1beta.types import analytics_admin +from google.analytics.admin_v1beta.types import resources +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 .transports.base import AnalyticsAdminServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AnalyticsAdminServiceGrpcTransport +from .transports.grpc_asyncio import AnalyticsAdminServiceGrpcAsyncIOTransport +from .transports.rest import AnalyticsAdminServiceRestTransport + + +class AnalyticsAdminServiceClientMeta(type): + """Metaclass for the AnalyticsAdminService 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[AnalyticsAdminServiceTransport]] + _transport_registry["grpc"] = AnalyticsAdminServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AnalyticsAdminServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AnalyticsAdminServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AnalyticsAdminServiceTransport]: + """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 AnalyticsAdminServiceClient(metaclass=AnalyticsAdminServiceClientMeta): + """Service Interface for the Analytics Admin API (GA4).""" + + @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 = "analyticsadmin.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "analyticsadmin.{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: + AnalyticsAdminServiceClient: 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: + AnalyticsAdminServiceClient: 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) -> AnalyticsAdminServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AnalyticsAdminServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def account_path(account: str,) -> str: + """Returns a fully-qualified account string.""" + return "accounts/{account}".format(account=account, ) + + @staticmethod + def parse_account_path(path: str) -> Dict[str,str]: + """Parses a account path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def account_summary_path(account_summary: str,) -> str: + """Returns a fully-qualified account_summary string.""" + return "accountSummaries/{account_summary}".format(account_summary=account_summary, ) + + @staticmethod + def parse_account_summary_path(path: str) -> Dict[str,str]: + """Parses a account_summary path into its component segments.""" + m = re.match(r"^accountSummaries/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def conversion_event_path(property: str,conversion_event: str,) -> str: + """Returns a fully-qualified conversion_event string.""" + return "properties/{property}/conversionEvents/{conversion_event}".format(property=property, conversion_event=conversion_event, ) + + @staticmethod + def parse_conversion_event_path(path: str) -> Dict[str,str]: + """Parses a conversion_event path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/conversionEvents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def custom_dimension_path(property: str,custom_dimension: str,) -> str: + """Returns a fully-qualified custom_dimension string.""" + return "properties/{property}/customDimensions/{custom_dimension}".format(property=property, custom_dimension=custom_dimension, ) + + @staticmethod + def parse_custom_dimension_path(path: str) -> Dict[str,str]: + """Parses a custom_dimension path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/customDimensions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def custom_metric_path(property: str,custom_metric: str,) -> str: + """Returns a fully-qualified custom_metric string.""" + return "properties/{property}/customMetrics/{custom_metric}".format(property=property, custom_metric=custom_metric, ) + + @staticmethod + def parse_custom_metric_path(path: str) -> Dict[str,str]: + """Parses a custom_metric path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/customMetrics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_retention_settings_path(property: str,) -> str: + """Returns a fully-qualified data_retention_settings string.""" + return "properties/{property}/dataRetentionSettings".format(property=property, ) + + @staticmethod + def parse_data_retention_settings_path(path: str) -> Dict[str,str]: + """Parses a data_retention_settings path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataRetentionSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_sharing_settings_path(account: str,) -> str: + """Returns a fully-qualified data_sharing_settings string.""" + return "accounts/{account}/dataSharingSettings".format(account=account, ) + + @staticmethod + def parse_data_sharing_settings_path(path: str) -> Dict[str,str]: + """Parses a data_sharing_settings path into its component segments.""" + m = re.match(r"^accounts/(?P.+?)/dataSharingSettings$", path) + return m.groupdict() if m else {} + + @staticmethod + def data_stream_path(property: str,data_stream: str,) -> str: + """Returns a fully-qualified data_stream string.""" + return "properties/{property}/dataStreams/{data_stream}".format(property=property, data_stream=data_stream, ) + + @staticmethod + def parse_data_stream_path(path: str) -> Dict[str,str]: + """Parses a data_stream path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def firebase_link_path(property: str,firebase_link: str,) -> str: + """Returns a fully-qualified firebase_link string.""" + return "properties/{property}/firebaseLinks/{firebase_link}".format(property=property, firebase_link=firebase_link, ) + + @staticmethod + def parse_firebase_link_path(path: str) -> Dict[str,str]: + """Parses a firebase_link path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/firebaseLinks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def google_ads_link_path(property: str,google_ads_link: str,) -> str: + """Returns a fully-qualified google_ads_link string.""" + return "properties/{property}/googleAdsLinks/{google_ads_link}".format(property=property, google_ads_link=google_ads_link, ) + + @staticmethod + def parse_google_ads_link_path(path: str) -> Dict[str,str]: + """Parses a google_ads_link path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/googleAdsLinks/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def key_event_path(property: str,key_event: str,) -> str: + """Returns a fully-qualified key_event string.""" + return "properties/{property}/keyEvents/{key_event}".format(property=property, key_event=key_event, ) + + @staticmethod + def parse_key_event_path(path: str) -> Dict[str,str]: + """Parses a key_event path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/keyEvents/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def measurement_protocol_secret_path(property: str,data_stream: str,measurement_protocol_secret: str,) -> str: + """Returns a fully-qualified measurement_protocol_secret string.""" + return "properties/{property}/dataStreams/{data_stream}/measurementProtocolSecrets/{measurement_protocol_secret}".format(property=property, data_stream=data_stream, measurement_protocol_secret=measurement_protocol_secret, ) + + @staticmethod + def parse_measurement_protocol_secret_path(path: str) -> Dict[str,str]: + """Parses a measurement_protocol_secret path into its component segments.""" + m = re.match(r"^properties/(?P.+?)/dataStreams/(?P.+?)/measurementProtocolSecrets/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def organization_path(organization: str,) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_organization_path(path: str) -> Dict[str,str]: + """Parses a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def property_path(property: str,) -> str: + """Returns a fully-qualified property string.""" + return "properties/{property}".format(property=property, ) + + @staticmethod + def parse_property_path(path: str) -> Dict[str,str]: + """Parses a property path into its component segments.""" + m = re.match(r"^properties/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AnalyticsAdminServiceClient._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 = AnalyticsAdminServiceClient._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 = AnalyticsAdminServiceClient._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 + AnalyticsAdminServiceClient._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, AnalyticsAdminServiceTransport, Callable[..., AnalyticsAdminServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the analytics admin service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AnalyticsAdminServiceTransport,Callable[..., AnalyticsAdminServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AnalyticsAdminServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AnalyticsAdminServiceClient._read_environment_variables() + self._client_cert_source = AnalyticsAdminServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AnalyticsAdminServiceClient._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, AnalyticsAdminServiceTransport) + if transport_provided: + # transport is a AnalyticsAdminServiceTransport 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(AnalyticsAdminServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AnalyticsAdminServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AnalyticsAdminServiceTransport], Callable[..., AnalyticsAdminServiceTransport]] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AnalyticsAdminServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def get_account(self, + request: Optional[Union[analytics_admin.GetAccountRequest, 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]] = (), + ) -> resources.Account: + r"""Lookup for a single Account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = client.get_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetAccountRequest, dict]): + The request object. Request message for GetAccount RPC. + name (str): + Required. The name of the account to + lookup. Format: accounts/{account} + Example: "accounts/100" + + 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.analytics.admin_v1beta.types.Account: + A resource message representing a + Google Analytics account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetAccountRequest): + request = analytics_admin.GetAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_accounts(self, + request: Optional[Union[analytics_admin.ListAccountsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAccountsPager: + r"""Returns all accounts accessible by the caller. + + Note that these accounts might not currently have GA4 + properties. Soft-deleted (ie: "trashed") accounts are + excluded by default. Returns an empty list if no + relevant accounts are found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_accounts(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListAccountsRequest, dict]): + The request object. Request message for ListAccounts RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListAccountsPager: + Request message for ListAccounts RPC. + + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccountsRequest): + request = analytics_admin.ListAccountsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_accounts] + + # 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.ListAccountsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_account(self, + request: Optional[Union[analytics_admin.DeleteAccountRequest, 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"""Marks target Account as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + accounts. However, they can be restored using the Trash + Can UI. + + If the accounts are not restored before the expiration + time, the account and all child resources (eg: + Properties, GoogleAdsLinks, Streams, AccessBindings) + will be permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_delete_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + client.delete_account(request=request) + + Args: + request (Union[google.analytics.admin_v1beta.types.DeleteAccountRequest, dict]): + The request object. Request message for DeleteAccount + RPC. + name (str): + Required. The name of the Account to + soft-delete. Format: accounts/{account} + Example: "accounts/100" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteAccountRequest): + request = analytics_admin.DeleteAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_account] + + # Certain fields should be provided within 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 update_account(self, + request: Optional[Union[analytics_admin.UpdateAccountRequest, dict]] = None, + *, + account: Optional[resources.Account] = 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]] = (), + ) -> resources.Account: + r"""Updates an account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + account = admin_v1beta.Account() + account.display_name = "display_name_value" + + request = admin_v1beta.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = client.update_account(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdateAccountRequest, dict]): + The request object. Request message for UpdateAccount + RPC. + account (google.analytics.admin_v1beta.types.Account): + Required. The account to update. The account's ``name`` + field is used to identify the account. + + This corresponds to the ``account`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (for example, "field_to_update"). + Omitted fields will not be updated. To replace the + entire entity, use one path with the string "*" to match + all fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.Account: + A resource message representing a + Google Analytics account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([account, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateAccountRequest): + request = analytics_admin.UpdateAccountRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if account is not None: + request.account = account + 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_account] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account.name", request.account.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 provision_account_ticket(self, + request: Optional[Union[analytics_admin.ProvisionAccountTicketRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.ProvisionAccountTicketResponse: + r"""Requests a ticket for creating an account. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_provision_account_ticket(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ProvisionAccountTicketRequest( + ) + + # Make the request + response = client.provision_account_ticket(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ProvisionAccountTicketRequest, dict]): + The request object. Request message for + ProvisionAccountTicket RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.ProvisionAccountTicketResponse: + Response message for + ProvisionAccountTicket RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ProvisionAccountTicketRequest): + request = analytics_admin.ProvisionAccountTicketRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.provision_account_ticket] + + # 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_account_summaries(self, + request: Optional[Union[analytics_admin.ListAccountSummariesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAccountSummariesPager: + r"""Returns summaries of all accounts accessible by the + caller. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_account_summaries(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListAccountSummariesRequest( + ) + + # Make the request + page_result = client.list_account_summaries(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListAccountSummariesRequest, dict]): + The request object. Request message for + ListAccountSummaries RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListAccountSummariesPager: + Response message for + ListAccountSummaries RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListAccountSummariesRequest): + request = analytics_admin.ListAccountSummariesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_account_summaries] + + # 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.ListAccountSummariesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_property(self, + request: Optional[Union[analytics_admin.GetPropertyRequest, 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]] = (), + ) -> resources.Property: + r"""Lookup for a single "GA4" Property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetPropertyRequest( + name="name_value", + ) + + # Make the request + response = client.get_property(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetPropertyRequest, dict]): + The request object. Request message for GetProperty RPC. + name (str): + Required. The name of the property to lookup. Format: + properties/{property_id} Example: "properties/1000" + + 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.analytics.admin_v1beta.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetPropertyRequest): + request = analytics_admin.GetPropertyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_property] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_properties(self, + request: Optional[Union[analytics_admin.ListPropertiesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListPropertiesPager: + r"""Returns child Properties under the specified parent + Account. + Only "GA4" properties will be returned. + Properties will be excluded if the caller does not have + access. Soft-deleted (ie: "trashed") properties are + excluded by default. Returns an empty list if no + relevant properties are found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_properties(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListPropertiesRequest( + filter="filter_value", + ) + + # Make the request + page_result = client.list_properties(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListPropertiesRequest, dict]): + The request object. Request message for ListProperties + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListPropertiesPager: + Response message for ListProperties + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListPropertiesRequest): + request = analytics_admin.ListPropertiesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_properties] + + # 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.ListPropertiesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_property(self, + request: Optional[Union[analytics_admin.CreatePropertyRequest, dict]] = None, + *, + property: Optional[resources.Property] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.Property: + r"""Creates an "GA4" property with the specified location + and attributes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_create_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + property = admin_v1beta.Property() + property.display_name = "display_name_value" + property.time_zone = "time_zone_value" + + request = admin_v1beta.CreatePropertyRequest( + property=property, + ) + + # Make the request + response = client.create_property(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.CreatePropertyRequest, dict]): + The request object. Request message for CreateProperty + RPC. + property (google.analytics.admin_v1beta.types.Property): + Required. The property to create. + Note: the supplied property must specify + its parent. + + This corresponds to the ``property`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([property]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreatePropertyRequest): + request = analytics_admin.CreatePropertyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if property is not None: + request.property = property + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_property] + + # 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_property(self, + request: Optional[Union[analytics_admin.DeletePropertyRequest, 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]] = (), + ) -> resources.Property: + r"""Marks target Property as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + properties. However, they can be restored using the + Trash Can UI. + + If the properties are not restored before the expiration + time, the Property and all child resources (eg: + GoogleAdsLinks, Streams, AccessBindings) will be + permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found, or is not a + GA4 Property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_delete_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeletePropertyRequest( + name="name_value", + ) + + # Make the request + response = client.delete_property(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.DeletePropertyRequest, dict]): + The request object. Request message for DeleteProperty + RPC. + name (str): + Required. The name of the Property to soft-delete. + Format: properties/{property_id} Example: + "properties/1000" + + 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.analytics.admin_v1beta.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeletePropertyRequest): + request = analytics_admin.DeletePropertyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_property] + + # Certain fields should be provided within 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_property(self, + request: Optional[Union[analytics_admin.UpdatePropertyRequest, dict]] = None, + *, + property: Optional[resources.Property] = 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]] = (), + ) -> resources.Property: + r"""Updates a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + property = admin_v1beta.Property() + property.display_name = "display_name_value" + property.time_zone = "time_zone_value" + + request = admin_v1beta.UpdatePropertyRequest( + property=property, + ) + + # Make the request + response = client.update_property(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdatePropertyRequest, dict]): + The request object. Request message for UpdateProperty + RPC. + property (google.analytics.admin_v1beta.types.Property): + Required. The property to update. The property's + ``name`` field is used to identify the property to be + updated. + + This corresponds to the ``property`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([property, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdatePropertyRequest): + request = analytics_admin.UpdatePropertyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if property is not None: + request.property = property + 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_property] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property.name", request.property.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_firebase_link(self, + request: Optional[Union[analytics_admin.CreateFirebaseLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + firebase_link: Optional[resources.FirebaseLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.FirebaseLink: + r"""Creates a FirebaseLink. + + Properties can have at most one FirebaseLink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_create_firebase_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateFirebaseLinkRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_firebase_link(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.CreateFirebaseLinkRequest, dict]): + The request object. Request message for + CreateFirebaseLink RPC + parent (str): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + firebase_link (google.analytics.admin_v1beta.types.FirebaseLink): + Required. The Firebase link to + create. + + This corresponds to the ``firebase_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.FirebaseLink: + A link between a GA4 property and a + Firebase project. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, firebase_link]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateFirebaseLinkRequest): + request = analytics_admin.CreateFirebaseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if firebase_link is not None: + request.firebase_link = firebase_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_firebase_link] + + # Certain 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 delete_firebase_link(self, + request: Optional[Union[analytics_admin.DeleteFirebaseLinkRequest, 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 FirebaseLink on a property + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_delete_firebase_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteFirebaseLinkRequest( + name="name_value", + ) + + # Make the request + client.delete_firebase_link(request=request) + + Args: + request (Union[google.analytics.admin_v1beta.types.DeleteFirebaseLinkRequest, dict]): + The request object. Request message for + DeleteFirebaseLink RPC + name (str): + Required. Format: + properties/{property_id}/firebaseLinks/{firebase_link_id} + + Example: ``properties/1234/firebaseLinks/5678`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteFirebaseLinkRequest): + request = analytics_admin.DeleteFirebaseLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_firebase_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_firebase_links(self, + request: Optional[Union[analytics_admin.ListFirebaseLinksRequest, 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.ListFirebaseLinksPager: + r"""Lists FirebaseLinks on a property. + Properties can have at most one FirebaseLink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_firebase_links(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListFirebaseLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_firebase_links(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListFirebaseLinksRequest, dict]): + The request object. Request message for ListFirebaseLinks + RPC + parent (str): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListFirebaseLinksPager: + Response message for + ListFirebaseLinks RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListFirebaseLinksRequest): + request = analytics_admin.ListFirebaseLinksRequest(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_firebase_links] + + # Certain 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.ListFirebaseLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_google_ads_link(self, + request: Optional[Union[analytics_admin.CreateGoogleAdsLinkRequest, dict]] = None, + *, + parent: Optional[str] = None, + google_ads_link: Optional[resources.GoogleAdsLink] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.GoogleAdsLink: + r"""Creates a GoogleAdsLink. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_create_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateGoogleAdsLinkRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_google_ads_link(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.CreateGoogleAdsLinkRequest, dict]): + The request object. Request message for + CreateGoogleAdsLink RPC + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + google_ads_link (google.analytics.admin_v1beta.types.GoogleAdsLink): + Required. The GoogleAdsLink to + create. + + This corresponds to the ``google_ads_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, google_ads_link]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateGoogleAdsLinkRequest): + request = analytics_admin.CreateGoogleAdsLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if google_ads_link is not None: + request.google_ads_link = google_ads_link + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_google_ads_link] + + # Certain 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_google_ads_link(self, + request: Optional[Union[analytics_admin.UpdateGoogleAdsLinkRequest, dict]] = None, + *, + google_ads_link: Optional[resources.GoogleAdsLink] = 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]] = (), + ) -> resources.GoogleAdsLink: + r"""Updates a GoogleAdsLink on a property + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateGoogleAdsLinkRequest( + ) + + # Make the request + response = client.update_google_ads_link(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdateGoogleAdsLinkRequest, dict]): + The request object. Request message for + UpdateGoogleAdsLink RPC + google_ads_link (google.analytics.admin_v1beta.types.GoogleAdsLink): + The GoogleAdsLink to update + This corresponds to the ``google_ads_link`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([google_ads_link, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateGoogleAdsLinkRequest): + request = analytics_admin.UpdateGoogleAdsLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if google_ads_link is not None: + request.google_ads_link = google_ads_link + 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_google_ads_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("google_ads_link.name", request.google_ads_link.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_google_ads_link(self, + request: Optional[Union[analytics_admin.DeleteGoogleAdsLinkRequest, 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 GoogleAdsLink on a property + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_delete_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteGoogleAdsLinkRequest( + name="name_value", + ) + + # Make the request + client.delete_google_ads_link(request=request) + + Args: + request (Union[google.analytics.admin_v1beta.types.DeleteGoogleAdsLinkRequest, dict]): + The request object. Request message for + DeleteGoogleAdsLink RPC. + name (str): + Required. Example format: + properties/1234/googleAdsLinks/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteGoogleAdsLinkRequest): + request = analytics_admin.DeleteGoogleAdsLinkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_google_ads_link] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_google_ads_links(self, + request: Optional[Union[analytics_admin.ListGoogleAdsLinksRequest, 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.ListGoogleAdsLinksPager: + r"""Lists GoogleAdsLinks on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_google_ads_links(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListGoogleAdsLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_ads_links(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListGoogleAdsLinksRequest, dict]): + The request object. Request message for + ListGoogleAdsLinks RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListGoogleAdsLinksPager: + Response message for + ListGoogleAdsLinks RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListGoogleAdsLinksRequest): + request = analytics_admin.ListGoogleAdsLinksRequest(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_google_ads_links] + + # Certain 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.ListGoogleAdsLinksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_data_sharing_settings(self, + request: Optional[Union[analytics_admin.GetDataSharingSettingsRequest, 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]] = (), + ) -> resources.DataSharingSettings: + r"""Get data sharing settings on an account. + Data sharing settings are singletons. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_data_sharing_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataSharingSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_sharing_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetDataSharingSettingsRequest, dict]): + The request object. Request message for + GetDataSharingSettings RPC. + name (str): + Required. The name of the settings to lookup. Format: + accounts/{account}/dataSharingSettings + + Example: ``accounts/1000/dataSharingSettings`` + + 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.analytics.admin_v1beta.types.DataSharingSettings: + A resource message representing data + sharing settings of a Google Analytics + account. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataSharingSettingsRequest): + request = analytics_admin.GetDataSharingSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_data_sharing_settings] + + # Certain fields should be provided within 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_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.GetMeasurementProtocolSecretRequest, 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]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Lookup for a single "GA4" MeasurementProtocolSecret. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetMeasurementProtocolSecretRequest( + name="name_value", + ) + + # Make the request + response = client.get_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetMeasurementProtocolSecretRequest, dict]): + The request object. Request message for + GetMeasurementProtocolSecret RPC. + name (str): + Required. The name of the measurement + protocol secret to lookup. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + + 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.analytics.admin_v1beta.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetMeasurementProtocolSecretRequest): + request = analytics_admin.GetMeasurementProtocolSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_measurement_protocol_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_measurement_protocol_secrets(self, + request: Optional[Union[analytics_admin.ListMeasurementProtocolSecretsRequest, 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.ListMeasurementProtocolSecretsPager: + r"""Returns child MeasurementProtocolSecrets under the + specified parent Property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_measurement_protocol_secrets(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListMeasurementProtocolSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_measurement_protocol_secrets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsRequest, dict]): + The request object. Request message for + ListMeasurementProtocolSecret RPC + parent (str): + Required. The resource name of the + parent stream. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListMeasurementProtocolSecretsPager: + Response message for + ListMeasurementProtocolSecret RPC + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListMeasurementProtocolSecretsRequest): + request = analytics_admin.ListMeasurementProtocolSecretsRequest(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_measurement_protocol_secrets] + + # Certain 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.ListMeasurementProtocolSecretsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.CreateMeasurementProtocolSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + measurement_protocol_secret: Optional[resources.MeasurementProtocolSecret] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Creates a measurement protocol secret. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_create_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + measurement_protocol_secret = admin_v1beta.MeasurementProtocolSecret() + measurement_protocol_secret.display_name = "display_name_value" + + request = admin_v1beta.CreateMeasurementProtocolSecretRequest( + parent="parent_value", + measurement_protocol_secret=measurement_protocol_secret, + ) + + # Make the request + response = client.create_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.CreateMeasurementProtocolSecretRequest, dict]): + The request object. Request message for + CreateMeasurementProtocolSecret RPC + parent (str): + Required. The parent resource where + this secret will be created. Format: + properties/{property}/dataStreams/{dataStream} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + measurement_protocol_secret (google.analytics.admin_v1beta.types.MeasurementProtocolSecret): + Required. The measurement protocol + secret to create. + + This corresponds to the ``measurement_protocol_secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, measurement_protocol_secret]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateMeasurementProtocolSecretRequest): + request = analytics_admin.CreateMeasurementProtocolSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if measurement_protocol_secret is not None: + request.measurement_protocol_secret = measurement_protocol_secret + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_measurement_protocol_secret] + + # Certain 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 delete_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.DeleteMeasurementProtocolSecretRequest, 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 target MeasurementProtocolSecret. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_delete_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteMeasurementProtocolSecretRequest( + name="name_value", + ) + + # Make the request + client.delete_measurement_protocol_secret(request=request) + + Args: + request (Union[google.analytics.admin_v1beta.types.DeleteMeasurementProtocolSecretRequest, dict]): + The request object. Request message for + DeleteMeasurementProtocolSecret RPC + name (str): + Required. The name of the + MeasurementProtocolSecret to delete. + Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteMeasurementProtocolSecretRequest): + request = analytics_admin.DeleteMeasurementProtocolSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_measurement_protocol_secret] + + # Certain fields should be provided within 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 update_measurement_protocol_secret(self, + request: Optional[Union[analytics_admin.UpdateMeasurementProtocolSecretRequest, dict]] = None, + *, + measurement_protocol_secret: Optional[resources.MeasurementProtocolSecret] = 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]] = (), + ) -> resources.MeasurementProtocolSecret: + r"""Updates a measurement protocol secret. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + measurement_protocol_secret = admin_v1beta.MeasurementProtocolSecret() + measurement_protocol_secret.display_name = "display_name_value" + + request = admin_v1beta.UpdateMeasurementProtocolSecretRequest( + measurement_protocol_secret=measurement_protocol_secret, + ) + + # Make the request + response = client.update_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdateMeasurementProtocolSecretRequest, dict]): + The request object. Request message for + UpdateMeasurementProtocolSecret RPC + measurement_protocol_secret (google.analytics.admin_v1beta.types.MeasurementProtocolSecret): + Required. The measurement protocol + secret to update. + + This corresponds to the ``measurement_protocol_secret`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be + updated. Omitted fields will not be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([measurement_protocol_secret, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateMeasurementProtocolSecretRequest): + request = analytics_admin.UpdateMeasurementProtocolSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if measurement_protocol_secret is not None: + request.measurement_protocol_secret = measurement_protocol_secret + 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_measurement_protocol_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("measurement_protocol_secret.name", request.measurement_protocol_secret.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 acknowledge_user_data_collection(self, + request: Optional[Union[analytics_admin.AcknowledgeUserDataCollectionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.AcknowledgeUserDataCollectionResponse: + r"""Acknowledges the terms of user data collection for + the specified property. + This acknowledgement must be completed (either in the + Google Analytics UI or through this API) before + MeasurementProtocolSecret resources may be created. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_acknowledge_user_data_collection(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.AcknowledgeUserDataCollectionRequest( + property="property_value", + acknowledgement="acknowledgement_value", + ) + + # Make the request + response = client.acknowledge_user_data_collection(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.AcknowledgeUserDataCollectionRequest, dict]): + The request object. Request message for + AcknowledgeUserDataCollection RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.AcknowledgeUserDataCollectionResponse: + Response message for + AcknowledgeUserDataCollection RPC. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.AcknowledgeUserDataCollectionRequest): + request = analytics_admin.AcknowledgeUserDataCollectionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.acknowledge_user_data_collection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("property", request.property), + )), + ) + + # 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 search_change_history_events(self, + request: Optional[Union[analytics_admin.SearchChangeHistoryEventsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchChangeHistoryEventsPager: + r"""Searches through all changes to an account or its + children given the specified set of filters. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_search_change_history_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.SearchChangeHistoryEventsRequest( + account="account_value", + ) + + # Make the request + page_result = client.search_change_history_events(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.SearchChangeHistoryEventsRequest, dict]): + The request object. Request message for + SearchChangeHistoryEvents RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.services.analytics_admin_service.pagers.SearchChangeHistoryEventsPager: + Response message for SearchAccounts + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.SearchChangeHistoryEventsRequest): + request = analytics_admin.SearchChangeHistoryEventsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_change_history_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("account", request.account), + )), + ) + + # 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.SearchChangeHistoryEventsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_conversion_event(self, + request: Optional[Union[analytics_admin.CreateConversionEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + conversion_event: Optional[resources.ConversionEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_create_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateConversionEventRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_conversion_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.CreateConversionEventRequest, dict]): + The request object. Request message for + CreateConversionEvent RPC + parent (str): + Required. The resource name of the + parent property where this conversion + event will be created. Format: + properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + conversion_event (google.analytics.admin_v1beta.types.ConversionEvent): + Required. The conversion event to + create. + + This corresponds to the ``conversion_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceClient.create_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, conversion_event]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateConversionEventRequest): + request = analytics_admin.CreateConversionEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if conversion_event is not None: + request.conversion_event = conversion_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_conversion_event(self, + request: Optional[Union[analytics_admin.UpdateConversionEventRequest, dict]] = None, + *, + conversion_event: Optional[resources.ConversionEvent] = 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]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateConversionEventRequest( + ) + + # Make the request + response = client.update_conversion_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdateConversionEventRequest, dict]): + The request object. Request message for + UpdateConversionEvent RPC + conversion_event (google.analytics.admin_v1beta.types.ConversionEvent): + Required. The conversion event to update. The ``name`` + field is used to identify the settings to be updated. + + This corresponds to the ``conversion_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceClient.update_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([conversion_event, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateConversionEventRequest): + request = analytics_admin.UpdateConversionEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversion_event is not None: + request.conversion_event = conversion_event + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("conversion_event.name", request.conversion_event.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_conversion_event(self, + request: Optional[Union[analytics_admin.GetConversionEventRequest, 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]] = (), + ) -> resources.ConversionEvent: + r"""Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetConversionEventRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversion_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetConversionEventRequest, dict]): + The request object. Request message for + GetConversionEvent RPC + name (str): + Required. The resource name of the conversion event to + retrieve. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456" + + 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.analytics.admin_v1beta.types.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + warnings.warn("AnalyticsAdminServiceClient.get_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetConversionEventRequest): + request = analytics_admin.GetConversionEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_conversion_event(self, + request: Optional[Union[analytics_admin.DeleteConversionEventRequest, 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"""Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_delete_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteConversionEventRequest( + name="name_value", + ) + + # Make the request + client.delete_conversion_event(request=request) + + Args: + request (Union[google.analytics.admin_v1beta.types.DeleteConversionEventRequest, dict]): + The request object. Request message for + DeleteConversionEvent RPC + name (str): + Required. The resource name of the conversion event to + delete. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456" + + 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. + """ + warnings.warn("AnalyticsAdminServiceClient.delete_conversion_event is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteConversionEventRequest): + request = analytics_admin.DeleteConversionEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_conversion_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_conversion_events(self, + request: Optional[Union[analytics_admin.ListConversionEventsRequest, 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.ListConversionEventsPager: + r"""Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + + Returns an empty list if no conversion events are found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_conversion_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListConversionEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversion_events(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListConversionEventsRequest, dict]): + The request object. Request message for + ListConversionEvents RPC + parent (str): + Required. The resource name of the + parent property. Example: + 'properties/123' + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListConversionEventsPager: + Response message for + ListConversionEvents RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + warnings.warn("AnalyticsAdminServiceClient.list_conversion_events is deprecated", + DeprecationWarning) + + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListConversionEventsRequest): + request = analytics_admin.ListConversionEventsRequest(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_conversion_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListConversionEventsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_key_event(self, + request: Optional[Union[analytics_admin.CreateKeyEventRequest, dict]] = None, + *, + parent: Optional[str] = None, + key_event: Optional[resources.KeyEvent] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyEvent: + r"""Creates a Key Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_create_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + key_event = admin_v1beta.KeyEvent() + key_event.counting_method = "ONCE_PER_SESSION" + + request = admin_v1beta.CreateKeyEventRequest( + key_event=key_event, + parent="parent_value", + ) + + # Make the request + response = client.create_key_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.CreateKeyEventRequest, dict]): + The request object. Request message for CreateKeyEvent + RPC + parent (str): + Required. The resource name of the + parent property where this Key Event + will be created. Format: properties/123 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_event (google.analytics.admin_v1beta.types.KeyEvent): + Required. The Key Event to create. + This corresponds to the ``key_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, key_event]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateKeyEventRequest): + request = analytics_admin.CreateKeyEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_event is not None: + request.key_event = key_event + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_key_event(self, + request: Optional[Union[analytics_admin.UpdateKeyEventRequest, dict]] = None, + *, + key_event: Optional[resources.KeyEvent] = 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]] = (), + ) -> resources.KeyEvent: + r"""Updates a Key Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + key_event = admin_v1beta.KeyEvent() + key_event.counting_method = "ONCE_PER_SESSION" + + request = admin_v1beta.UpdateKeyEventRequest( + key_event=key_event, + ) + + # Make the request + response = client.update_key_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdateKeyEventRequest, dict]): + The request object. Request message for UpdateKeyEvent + RPC + key_event (google.analytics.admin_v1beta.types.KeyEvent): + Required. The Key Event to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``key_event`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([key_event, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateKeyEventRequest): + request = analytics_admin.UpdateKeyEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if key_event is not None: + request.key_event = key_event + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("key_event.name", request.key_event.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_key_event(self, + request: Optional[Union[analytics_admin.GetKeyEventRequest, 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]] = (), + ) -> resources.KeyEvent: + r"""Retrieve a single Key Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetKeyEventRequest( + name="name_value", + ) + + # Make the request + response = client.get_key_event(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetKeyEventRequest, dict]): + The request object. Request message for GetKeyEvent RPC + name (str): + Required. The resource name of the Key Event to + retrieve. Format: + properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456" + + 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.analytics.admin_v1beta.types.KeyEvent: + A key event in a Google Analytics + property. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetKeyEventRequest): + request = analytics_admin.GetKeyEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_key_event(self, + request: Optional[Union[analytics_admin.DeleteKeyEventRequest, 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 Key Event. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_delete_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteKeyEventRequest( + name="name_value", + ) + + # Make the request + client.delete_key_event(request=request) + + Args: + request (Union[google.analytics.admin_v1beta.types.DeleteKeyEventRequest, dict]): + The request object. Request message for DeleteKeyEvent + RPC + name (str): + Required. The resource name of the Key Event to delete. + Format: properties/{property}/keyEvents/{key_event} + Example: "properties/123/keyEvents/456" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteKeyEventRequest): + request = analytics_admin.DeleteKeyEventRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_key_event] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_key_events(self, + request: Optional[Union[analytics_admin.ListKeyEventsRequest, 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.ListKeyEventsPager: + r"""Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_key_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListKeyEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_events(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListKeyEventsRequest, dict]): + The request object. Request message for ListKeyEvents RPC + parent (str): + Required. The resource name of the + parent property. Example: + 'properties/123' + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListKeyEventsPager: + Response message for ListKeyEvents + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListKeyEventsRequest): + request = analytics_admin.ListKeyEventsRequest(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_key_events] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListKeyEventsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_custom_dimension(self, + request: Optional[Union[analytics_admin.CreateCustomDimensionRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_dimension: Optional[resources.CustomDimension] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CustomDimension: + r"""Creates a CustomDimension. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_create_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + custom_dimension = admin_v1beta.CustomDimension() + custom_dimension.parameter_name = "parameter_name_value" + custom_dimension.display_name = "display_name_value" + custom_dimension.scope = "ITEM" + + request = admin_v1beta.CreateCustomDimensionRequest( + parent="parent_value", + custom_dimension=custom_dimension, + ) + + # Make the request + response = client.create_custom_dimension(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.CreateCustomDimensionRequest, dict]): + The request object. Request message for + CreateCustomDimension RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_dimension (google.analytics.admin_v1beta.types.CustomDimension): + Required. The CustomDimension to + create. + + This corresponds to the ``custom_dimension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_dimension]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCustomDimensionRequest): + request = analytics_admin.CreateCustomDimensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_dimension is not None: + request.custom_dimension = custom_dimension + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_custom_dimension] + + # Certain 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_custom_dimension(self, + request: Optional[Union[analytics_admin.UpdateCustomDimensionRequest, dict]] = None, + *, + custom_dimension: Optional[resources.CustomDimension] = 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]] = (), + ) -> resources.CustomDimension: + r"""Updates a CustomDimension on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateCustomDimensionRequest( + ) + + # Make the request + response = client.update_custom_dimension(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdateCustomDimensionRequest, dict]): + The request object. Request message for + UpdateCustomDimension RPC. + custom_dimension (google.analytics.admin_v1beta.types.CustomDimension): + The CustomDimension to update + This corresponds to the ``custom_dimension`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_dimension, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCustomDimensionRequest): + request = analytics_admin.UpdateCustomDimensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_dimension is not None: + request.custom_dimension = custom_dimension + 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_custom_dimension] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("custom_dimension.name", request.custom_dimension.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_custom_dimensions(self, + request: Optional[Union[analytics_admin.ListCustomDimensionsRequest, 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.ListCustomDimensionsPager: + r"""Lists CustomDimensions on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_custom_dimensions(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListCustomDimensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_dimensions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListCustomDimensionsRequest, dict]): + The request object. Request message for + ListCustomDimensions RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListCustomDimensionsPager: + Response message for + ListCustomDimensions RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCustomDimensionsRequest): + request = analytics_admin.ListCustomDimensionsRequest(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_custom_dimensions] + + # Certain 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.ListCustomDimensionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def archive_custom_dimension(self, + request: Optional[Union[analytics_admin.ArchiveCustomDimensionRequest, 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"""Archives a CustomDimension on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_archive_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ArchiveCustomDimensionRequest( + name="name_value", + ) + + # Make the request + client.archive_custom_dimension(request=request) + + Args: + request (Union[google.analytics.admin_v1beta.types.ArchiveCustomDimensionRequest, dict]): + The request object. Request message for + ArchiveCustomDimension RPC. + name (str): + Required. The name of the + CustomDimension to archive. Example + format: + properties/1234/customDimensions/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveCustomDimensionRequest): + request = analytics_admin.ArchiveCustomDimensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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.archive_custom_dimension] + + # Certain fields should be provided within 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_custom_dimension(self, + request: Optional[Union[analytics_admin.GetCustomDimensionRequest, 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]] = (), + ) -> resources.CustomDimension: + r"""Lookup for a single CustomDimension. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetCustomDimensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_custom_dimension(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetCustomDimensionRequest, dict]): + The request object. Request message for + GetCustomDimension RPC. + name (str): + Required. The name of the + CustomDimension to get. Example format: + properties/1234/customDimensions/5678 + + 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.analytics.admin_v1beta.types.CustomDimension: + A definition for a CustomDimension. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCustomDimensionRequest): + request = analytics_admin.GetCustomDimensionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_custom_dimension] + + # Certain fields should be provided within 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_custom_metric(self, + request: Optional[Union[analytics_admin.CreateCustomMetricRequest, dict]] = None, + *, + parent: Optional[str] = None, + custom_metric: Optional[resources.CustomMetric] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CustomMetric: + r"""Creates a CustomMetric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_create_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + custom_metric = admin_v1beta.CustomMetric() + custom_metric.parameter_name = "parameter_name_value" + custom_metric.display_name = "display_name_value" + custom_metric.measurement_unit = "HOURS" + custom_metric.scope = "EVENT" + + request = admin_v1beta.CreateCustomMetricRequest( + parent="parent_value", + custom_metric=custom_metric, + ) + + # Make the request + response = client.create_custom_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.CreateCustomMetricRequest, dict]): + The request object. Request message for + CreateCustomMetric RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + custom_metric (google.analytics.admin_v1beta.types.CustomMetric): + Required. The CustomMetric to create. + This corresponds to the ``custom_metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, custom_metric]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateCustomMetricRequest): + request = analytics_admin.CreateCustomMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if custom_metric is not None: + request.custom_metric = custom_metric + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_custom_metric] + + # Certain 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_custom_metric(self, + request: Optional[Union[analytics_admin.UpdateCustomMetricRequest, dict]] = None, + *, + custom_metric: Optional[resources.CustomMetric] = 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]] = (), + ) -> resources.CustomMetric: + r"""Updates a CustomMetric on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateCustomMetricRequest( + ) + + # Make the request + response = client.update_custom_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdateCustomMetricRequest, dict]): + The request object. Request message for + UpdateCustomMetric RPC. + custom_metric (google.analytics.admin_v1beta.types.CustomMetric): + The CustomMetric to update + This corresponds to the ``custom_metric`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([custom_metric, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateCustomMetricRequest): + request = analytics_admin.UpdateCustomMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if custom_metric is not None: + request.custom_metric = custom_metric + 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_custom_metric] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("custom_metric.name", request.custom_metric.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_custom_metrics(self, + request: Optional[Union[analytics_admin.ListCustomMetricsRequest, 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.ListCustomMetricsPager: + r"""Lists CustomMetrics on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_custom_metrics(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListCustomMetricsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_metrics(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListCustomMetricsRequest, dict]): + The request object. Request message for ListCustomMetrics + RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListCustomMetricsPager: + Response message for + ListCustomMetrics RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListCustomMetricsRequest): + request = analytics_admin.ListCustomMetricsRequest(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_custom_metrics] + + # Certain 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.ListCustomMetricsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def archive_custom_metric(self, + request: Optional[Union[analytics_admin.ArchiveCustomMetricRequest, 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"""Archives a CustomMetric on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_archive_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ArchiveCustomMetricRequest( + name="name_value", + ) + + # Make the request + client.archive_custom_metric(request=request) + + Args: + request (Union[google.analytics.admin_v1beta.types.ArchiveCustomMetricRequest, dict]): + The request object. Request message for + ArchiveCustomMetric RPC. + name (str): + Required. The name of the + CustomMetric to archive. Example format: + properties/1234/customMetrics/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ArchiveCustomMetricRequest): + request = analytics_admin.ArchiveCustomMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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.archive_custom_metric] + + # Certain fields should be provided within 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_custom_metric(self, + request: Optional[Union[analytics_admin.GetCustomMetricRequest, 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]] = (), + ) -> resources.CustomMetric: + r"""Lookup for a single CustomMetric. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetCustomMetricRequest( + name="name_value", + ) + + # Make the request + response = client.get_custom_metric(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetCustomMetricRequest, dict]): + The request object. Request message for GetCustomMetric + RPC. + name (str): + Required. The name of the + CustomMetric to get. Example format: + properties/1234/customMetrics/5678 + + 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.analytics.admin_v1beta.types.CustomMetric: + A definition for a custom metric. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetCustomMetricRequest): + request = analytics_admin.GetCustomMetricRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply 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_custom_metric] + + # Certain fields should be provided within 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_data_retention_settings(self, + request: Optional[Union[analytics_admin.GetDataRetentionSettingsRequest, 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]] = (), + ) -> resources.DataRetentionSettings: + r"""Returns the singleton data retention settings for + this property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_data_retention_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataRetentionSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_retention_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetDataRetentionSettingsRequest, dict]): + The request object. Request message for + GetDataRetentionSettings RPC. + name (str): + Required. The name of the settings to + lookup. Format: + + properties/{property}/dataRetentionSettings + Example: + "properties/1000/dataRetentionSettings" + + 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.analytics.admin_v1beta.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataRetentionSettingsRequest): + request = analytics_admin.GetDataRetentionSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_data_retention_settings] + + # Certain fields should be provided within 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_data_retention_settings(self, + request: Optional[Union[analytics_admin.UpdateDataRetentionSettingsRequest, dict]] = None, + *, + data_retention_settings: Optional[resources.DataRetentionSettings] = 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]] = (), + ) -> resources.DataRetentionSettings: + r"""Updates the singleton data retention settings for + this property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_data_retention_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateDataRetentionSettingsRequest( + ) + + # Make the request + response = client.update_data_retention_settings(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdateDataRetentionSettingsRequest, dict]): + The request object. Request message for + UpdateDataRetentionSettings RPC. + data_retention_settings (google.analytics.admin_v1beta.types.DataRetentionSettings): + Required. The settings to update. The ``name`` field is + used to identify the settings to be updated. + + This corresponds to the ``data_retention_settings`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names + must be in snake case (e.g., "field_to_update"). Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_retention_settings, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataRetentionSettingsRequest): + request = analytics_admin.UpdateDataRetentionSettingsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_retention_settings is not None: + request.data_retention_settings = data_retention_settings + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_data_retention_settings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_retention_settings.name", request.data_retention_settings.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_data_stream(self, + request: Optional[Union[analytics_admin.CreateDataStreamRequest, dict]] = None, + *, + parent: Optional[str] = None, + data_stream: Optional[resources.DataStream] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.DataStream: + r"""Creates a DataStream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_create_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + data_stream = admin_v1beta.DataStream() + data_stream.type_ = "IOS_APP_DATA_STREAM" + + request = admin_v1beta.CreateDataStreamRequest( + parent="parent_value", + data_stream=data_stream, + ) + + # Make the request + response = client.create_data_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.CreateDataStreamRequest, dict]): + The request object. Request message for CreateDataStream + RPC. + parent (str): + Required. Example format: + properties/1234 + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data_stream (google.analytics.admin_v1beta.types.DataStream): + Required. The DataStream to create. + This corresponds to the ``data_stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, data_stream]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.CreateDataStreamRequest): + request = analytics_admin.CreateDataStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if data_stream is not None: + request.data_stream = data_stream + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_data_stream(self, + request: Optional[Union[analytics_admin.DeleteDataStreamRequest, 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 DataStream on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_delete_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteDataStreamRequest( + name="name_value", + ) + + # Make the request + client.delete_data_stream(request=request) + + Args: + request (Union[google.analytics.admin_v1beta.types.DeleteDataStreamRequest, dict]): + The request object. Request message for DeleteDataStream + RPC. + name (str): + Required. The name of the DataStream + to delete. Example format: + properties/1234/dataStreams/5678 + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.DeleteDataStreamRequest): + request = analytics_admin.DeleteDataStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def update_data_stream(self, + request: Optional[Union[analytics_admin.UpdateDataStreamRequest, dict]] = None, + *, + data_stream: Optional[resources.DataStream] = 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]] = (), + ) -> resources.DataStream: + r"""Updates a DataStream on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_update_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateDataStreamRequest( + ) + + # Make the request + response = client.update_data_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.UpdateDataStreamRequest, dict]): + The request object. Request message for UpdateDataStream + RPC. + data_stream (google.analytics.admin_v1beta.types.DataStream): + The DataStream to update + This corresponds to the ``data_stream`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted + fields will not be updated. To replace the entire + entity, use one path with the string "*" to match all + fields. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([data_stream, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.UpdateDataStreamRequest): + request = analytics_admin.UpdateDataStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if data_stream is not None: + request.data_stream = data_stream + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("data_stream.name", request.data_stream.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_data_streams(self, + request: Optional[Union[analytics_admin.ListDataStreamsRequest, 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.ListDataStreamsPager: + r"""Lists DataStreams on a property. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_list_data_streams(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListDataStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_streams(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.ListDataStreamsRequest, dict]): + The request object. Request message for ListDataStreams + RPC. + parent (str): + Required. Example format: + properties/1234 + + 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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListDataStreamsPager: + Response message for ListDataStreams + RPC. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.ListDataStreamsRequest): + request = analytics_admin.ListDataStreamsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_data_streams] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDataStreamsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_data_stream(self, + request: Optional[Union[analytics_admin.GetDataStreamRequest, 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]] = (), + ) -> resources.DataStream: + r"""Lookup for a single DataStream. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_get_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataStreamRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_stream(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.GetDataStreamRequest, dict]): + The request object. Request message for GetDataStream + RPC. + name (str): + Required. The name of the DataStream + to get. Example format: + properties/1234/dataStreams/5678 + + 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.analytics.admin_v1beta.types.DataStream: + A resource message representing a + data stream. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.GetDataStreamRequest): + request = analytics_admin.GetDataStreamRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_data_stream] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def run_access_report(self, + request: Optional[Union[analytics_admin.RunAccessReportRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> analytics_admin.RunAccessReportResponse: + r"""Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. + + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.analytics import admin_v1beta + + def sample_run_access_report(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.RunAccessReportRequest( + ) + + # Make the request + response = client.run_access_report(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.analytics.admin_v1beta.types.RunAccessReportRequest, dict]): + The request object. The request for a Data Access Record + Report. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.analytics.admin_v1beta.types.RunAccessReportResponse: + The customized Data Access Record + Report response. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, analytics_admin.RunAccessReportRequest): + request = analytics_admin.RunAccessReportRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_access_report] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("entity", request.entity), + )), + ) + + # 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) -> "AnalyticsAdminServiceClient": + 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__ = ( + "AnalyticsAdminServiceClient", +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/pagers.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/pagers.py new file mode 100644 index 000000000000..6ae4652416ca --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/pagers.py @@ -0,0 +1,1648 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.analytics.admin_v1beta.types import analytics_admin +from google.analytics.admin_v1beta.types import resources + + +class ListAccountsPager: + """A pager for iterating through ``list_accounts`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListAccountsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListAccountsResponse` + 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[..., analytics_admin.ListAccountsResponse], + request: analytics_admin.ListAccountsRequest, + response: analytics_admin.ListAccountsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListAccountsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListAccountsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccountsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListAccountsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.Account]: + for page in self.pages: + yield from page.accounts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountsAsyncPager: + """A pager for iterating through ``list_accounts`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListAccountsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``accounts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccounts`` requests and continue to iterate + through the ``accounts`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListAccountsResponse` + 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[analytics_admin.ListAccountsResponse]], + request: analytics_admin.ListAccountsRequest, + response: analytics_admin.ListAccountsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListAccountsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListAccountsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccountsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListAccountsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.Account]: + async def async_generator(): + async for page in self.pages: + for response in page.accounts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountSummariesPager: + """A pager for iterating through ``list_account_summaries`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListAccountSummariesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``account_summaries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAccountSummaries`` requests and continue to iterate + through the ``account_summaries`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListAccountSummariesResponse` + 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[..., analytics_admin.ListAccountSummariesResponse], + request: analytics_admin.ListAccountSummariesRequest, + response: analytics_admin.ListAccountSummariesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListAccountSummariesRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListAccountSummariesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccountSummariesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListAccountSummariesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.AccountSummary]: + for page in self.pages: + yield from page.account_summaries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAccountSummariesAsyncPager: + """A pager for iterating through ``list_account_summaries`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListAccountSummariesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``account_summaries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAccountSummaries`` requests and continue to iterate + through the ``account_summaries`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListAccountSummariesResponse` + 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[analytics_admin.ListAccountSummariesResponse]], + request: analytics_admin.ListAccountSummariesRequest, + response: analytics_admin.ListAccountSummariesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListAccountSummariesRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListAccountSummariesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListAccountSummariesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListAccountSummariesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.AccountSummary]: + async def async_generator(): + async for page in self.pages: + for response in page.account_summaries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPropertiesPager: + """A pager for iterating through ``list_properties`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListPropertiesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``properties`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProperties`` requests and continue to iterate + through the ``properties`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListPropertiesResponse` + 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[..., analytics_admin.ListPropertiesResponse], + request: analytics_admin.ListPropertiesRequest, + response: analytics_admin.ListPropertiesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListPropertiesRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListPropertiesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListPropertiesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListPropertiesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.Property]: + for page in self.pages: + yield from page.properties + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListPropertiesAsyncPager: + """A pager for iterating through ``list_properties`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListPropertiesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``properties`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProperties`` requests and continue to iterate + through the ``properties`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListPropertiesResponse` + 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[analytics_admin.ListPropertiesResponse]], + request: analytics_admin.ListPropertiesRequest, + response: analytics_admin.ListPropertiesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListPropertiesRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListPropertiesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListPropertiesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListPropertiesResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.Property]: + async def async_generator(): + async for page in self.pages: + for response in page.properties: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFirebaseLinksPager: + """A pager for iterating through ``list_firebase_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListFirebaseLinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``firebase_links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFirebaseLinks`` requests and continue to iterate + through the ``firebase_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListFirebaseLinksResponse` + 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[..., analytics_admin.ListFirebaseLinksResponse], + request: analytics_admin.ListFirebaseLinksRequest, + response: analytics_admin.ListFirebaseLinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListFirebaseLinksRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListFirebaseLinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListFirebaseLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListFirebaseLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.FirebaseLink]: + for page in self.pages: + yield from page.firebase_links + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListFirebaseLinksAsyncPager: + """A pager for iterating through ``list_firebase_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListFirebaseLinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``firebase_links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFirebaseLinks`` requests and continue to iterate + through the ``firebase_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListFirebaseLinksResponse` + 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[analytics_admin.ListFirebaseLinksResponse]], + request: analytics_admin.ListFirebaseLinksRequest, + response: analytics_admin.ListFirebaseLinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListFirebaseLinksRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListFirebaseLinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListFirebaseLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListFirebaseLinksResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.FirebaseLink]: + async def async_generator(): + async for page in self.pages: + for response in page.firebase_links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGoogleAdsLinksPager: + """A pager for iterating through ``list_google_ads_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListGoogleAdsLinksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``google_ads_links`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGoogleAdsLinks`` requests and continue to iterate + through the ``google_ads_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListGoogleAdsLinksResponse` + 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[..., analytics_admin.ListGoogleAdsLinksResponse], + request: analytics_admin.ListGoogleAdsLinksRequest, + response: analytics_admin.ListGoogleAdsLinksResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListGoogleAdsLinksRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListGoogleAdsLinksResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListGoogleAdsLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListGoogleAdsLinksResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.GoogleAdsLink]: + for page in self.pages: + yield from page.google_ads_links + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListGoogleAdsLinksAsyncPager: + """A pager for iterating through ``list_google_ads_links`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListGoogleAdsLinksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``google_ads_links`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGoogleAdsLinks`` requests and continue to iterate + through the ``google_ads_links`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListGoogleAdsLinksResponse` + 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[analytics_admin.ListGoogleAdsLinksResponse]], + request: analytics_admin.ListGoogleAdsLinksRequest, + response: analytics_admin.ListGoogleAdsLinksResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListGoogleAdsLinksRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListGoogleAdsLinksResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListGoogleAdsLinksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListGoogleAdsLinksResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.GoogleAdsLink]: + async def async_generator(): + async for page in self.pages: + for response in page.google_ads_links: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMeasurementProtocolSecretsPager: + """A pager for iterating through ``list_measurement_protocol_secrets`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``measurement_protocol_secrets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListMeasurementProtocolSecrets`` requests and continue to iterate + through the ``measurement_protocol_secrets`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsResponse` + 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[..., analytics_admin.ListMeasurementProtocolSecretsResponse], + request: analytics_admin.ListMeasurementProtocolSecretsRequest, + response: analytics_admin.ListMeasurementProtocolSecretsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListMeasurementProtocolSecretsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListMeasurementProtocolSecretsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.MeasurementProtocolSecret]: + for page in self.pages: + yield from page.measurement_protocol_secrets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListMeasurementProtocolSecretsAsyncPager: + """A pager for iterating through ``list_measurement_protocol_secrets`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``measurement_protocol_secrets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListMeasurementProtocolSecrets`` requests and continue to iterate + through the ``measurement_protocol_secrets`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsResponse` + 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[analytics_admin.ListMeasurementProtocolSecretsResponse]], + request: analytics_admin.ListMeasurementProtocolSecretsRequest, + response: analytics_admin.ListMeasurementProtocolSecretsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListMeasurementProtocolSecretsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListMeasurementProtocolSecretsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.MeasurementProtocolSecret]: + async def async_generator(): + async for page in self.pages: + for response in page.measurement_protocol_secrets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchChangeHistoryEventsPager: + """A pager for iterating through ``search_change_history_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.SearchChangeHistoryEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``change_history_events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchChangeHistoryEvents`` requests and continue to iterate + through the ``change_history_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.SearchChangeHistoryEventsResponse` + 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[..., analytics_admin.SearchChangeHistoryEventsResponse], + request: analytics_admin.SearchChangeHistoryEventsRequest, + response: analytics_admin.SearchChangeHistoryEventsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.SearchChangeHistoryEventsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.SearchChangeHistoryEventsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.SearchChangeHistoryEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.SearchChangeHistoryEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.ChangeHistoryEvent]: + for page in self.pages: + yield from page.change_history_events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchChangeHistoryEventsAsyncPager: + """A pager for iterating through ``search_change_history_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.SearchChangeHistoryEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``change_history_events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchChangeHistoryEvents`` requests and continue to iterate + through the ``change_history_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.SearchChangeHistoryEventsResponse` + 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[analytics_admin.SearchChangeHistoryEventsResponse]], + request: analytics_admin.SearchChangeHistoryEventsRequest, + response: analytics_admin.SearchChangeHistoryEventsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.SearchChangeHistoryEventsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.SearchChangeHistoryEventsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.SearchChangeHistoryEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.SearchChangeHistoryEventsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.ChangeHistoryEvent]: + async def async_generator(): + async for page in self.pages: + for response in page.change_history_events: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversionEventsPager: + """A pager for iterating through ``list_conversion_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListConversionEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversion_events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversionEvents`` requests and continue to iterate + through the ``conversion_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListConversionEventsResponse` + 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[..., analytics_admin.ListConversionEventsResponse], + request: analytics_admin.ListConversionEventsRequest, + response: analytics_admin.ListConversionEventsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListConversionEventsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListConversionEventsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListConversionEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListConversionEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.ConversionEvent]: + for page in self.pages: + yield from page.conversion_events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListConversionEventsAsyncPager: + """A pager for iterating through ``list_conversion_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListConversionEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversion_events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversionEvents`` requests and continue to iterate + through the ``conversion_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListConversionEventsResponse` + 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[analytics_admin.ListConversionEventsResponse]], + request: analytics_admin.ListConversionEventsRequest, + response: analytics_admin.ListConversionEventsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListConversionEventsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListConversionEventsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListConversionEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListConversionEventsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.ConversionEvent]: + async def async_generator(): + async for page in self.pages: + for response in page.conversion_events: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListKeyEventsPager: + """A pager for iterating through ``list_key_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListKeyEventsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``key_events`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListKeyEvents`` requests and continue to iterate + through the ``key_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListKeyEventsResponse` + 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[..., analytics_admin.ListKeyEventsResponse], + request: analytics_admin.ListKeyEventsRequest, + response: analytics_admin.ListKeyEventsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListKeyEventsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListKeyEventsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListKeyEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListKeyEventsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.KeyEvent]: + for page in self.pages: + yield from page.key_events + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListKeyEventsAsyncPager: + """A pager for iterating through ``list_key_events`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListKeyEventsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``key_events`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListKeyEvents`` requests and continue to iterate + through the ``key_events`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListKeyEventsResponse` + 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[analytics_admin.ListKeyEventsResponse]], + request: analytics_admin.ListKeyEventsRequest, + response: analytics_admin.ListKeyEventsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListKeyEventsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListKeyEventsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListKeyEventsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListKeyEventsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.KeyEvent]: + async def async_generator(): + async for page in self.pages: + for response in page.key_events: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCustomDimensionsPager: + """A pager for iterating through ``list_custom_dimensions`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListCustomDimensionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``custom_dimensions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCustomDimensions`` requests and continue to iterate + through the ``custom_dimensions`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListCustomDimensionsResponse` + 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[..., analytics_admin.ListCustomDimensionsResponse], + request: analytics_admin.ListCustomDimensionsRequest, + response: analytics_admin.ListCustomDimensionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListCustomDimensionsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListCustomDimensionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCustomDimensionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListCustomDimensionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.CustomDimension]: + for page in self.pages: + yield from page.custom_dimensions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCustomDimensionsAsyncPager: + """A pager for iterating through ``list_custom_dimensions`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListCustomDimensionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``custom_dimensions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCustomDimensions`` requests and continue to iterate + through the ``custom_dimensions`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListCustomDimensionsResponse` + 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[analytics_admin.ListCustomDimensionsResponse]], + request: analytics_admin.ListCustomDimensionsRequest, + response: analytics_admin.ListCustomDimensionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListCustomDimensionsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListCustomDimensionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCustomDimensionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListCustomDimensionsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.CustomDimension]: + async def async_generator(): + async for page in self.pages: + for response in page.custom_dimensions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCustomMetricsPager: + """A pager for iterating through ``list_custom_metrics`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListCustomMetricsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``custom_metrics`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCustomMetrics`` requests and continue to iterate + through the ``custom_metrics`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListCustomMetricsResponse` + 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[..., analytics_admin.ListCustomMetricsResponse], + request: analytics_admin.ListCustomMetricsRequest, + response: analytics_admin.ListCustomMetricsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListCustomMetricsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListCustomMetricsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCustomMetricsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListCustomMetricsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.CustomMetric]: + for page in self.pages: + yield from page.custom_metrics + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCustomMetricsAsyncPager: + """A pager for iterating through ``list_custom_metrics`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListCustomMetricsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``custom_metrics`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCustomMetrics`` requests and continue to iterate + through the ``custom_metrics`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListCustomMetricsResponse` + 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[analytics_admin.ListCustomMetricsResponse]], + request: analytics_admin.ListCustomMetricsRequest, + response: analytics_admin.ListCustomMetricsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListCustomMetricsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListCustomMetricsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListCustomMetricsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListCustomMetricsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.CustomMetric]: + async def async_generator(): + async for page in self.pages: + for response in page.custom_metrics: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataStreamsPager: + """A pager for iterating through ``list_data_streams`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListDataStreamsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``data_streams`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDataStreams`` requests and continue to iterate + through the ``data_streams`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListDataStreamsResponse` + 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[..., analytics_admin.ListDataStreamsResponse], + request: analytics_admin.ListDataStreamsRequest, + response: analytics_admin.ListDataStreamsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListDataStreamsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListDataStreamsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListDataStreamsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[analytics_admin.ListDataStreamsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.DataStream]: + for page in self.pages: + yield from page.data_streams + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListDataStreamsAsyncPager: + """A pager for iterating through ``list_data_streams`` requests. + + This class thinly wraps an initial + :class:`google.analytics.admin_v1beta.types.ListDataStreamsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``data_streams`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDataStreams`` requests and continue to iterate + through the ``data_streams`` field on the + corresponding responses. + + All the usual :class:`google.analytics.admin_v1beta.types.ListDataStreamsResponse` + 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[analytics_admin.ListDataStreamsResponse]], + request: analytics_admin.ListDataStreamsRequest, + response: analytics_admin.ListDataStreamsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = ()): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.analytics.admin_v1beta.types.ListDataStreamsRequest): + The initial request object. + response (google.analytics.admin_v1beta.types.ListDataStreamsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = analytics_admin.ListDataStreamsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[analytics_admin.ListDataStreamsResponse]: + 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, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.DataStream]: + async def async_generator(): + async for page in self.pages: + for response in page.data_streams: + 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-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/__init__.py new file mode 100644 index 000000000000..76ffdcce4f9c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_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 AnalyticsAdminServiceTransport +from .grpc import AnalyticsAdminServiceGrpcTransport +from .grpc_asyncio import AnalyticsAdminServiceGrpcAsyncIOTransport +from .rest import AnalyticsAdminServiceRestTransport +from .rest import AnalyticsAdminServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AnalyticsAdminServiceTransport]] +_transport_registry['grpc'] = AnalyticsAdminServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AnalyticsAdminServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AnalyticsAdminServiceRestTransport + +__all__ = ( + 'AnalyticsAdminServiceTransport', + 'AnalyticsAdminServiceGrpcTransport', + 'AnalyticsAdminServiceGrpcAsyncIOTransport', + 'AnalyticsAdminServiceRestTransport', + 'AnalyticsAdminServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/base.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/base.py new file mode 100644 index 000000000000..43bb5320bd25 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/base.py @@ -0,0 +1,899 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1beta 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.analytics.admin_v1beta.types import analytics_admin +from google.analytics.admin_v1beta.types import resources +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AnalyticsAdminServiceTransport(abc.ABC): + """Abstract transport class for AnalyticsAdminService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/analytics.edit', + 'https://www.googleapis.com/auth/analytics.readonly', + ) + + DEFAULT_HOST: str = 'analyticsadmin.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: 'analyticsadmin.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 not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + 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.get_account: gapic_v1.method.wrap_method( + self.get_account, + default_timeout=None, + client_info=client_info, + ), + self.list_accounts: gapic_v1.method.wrap_method( + self.list_accounts, + default_timeout=None, + client_info=client_info, + ), + self.delete_account: gapic_v1.method.wrap_method( + self.delete_account, + default_timeout=None, + client_info=client_info, + ), + self.update_account: gapic_v1.method.wrap_method( + self.update_account, + default_timeout=None, + client_info=client_info, + ), + self.provision_account_ticket: gapic_v1.method.wrap_method( + self.provision_account_ticket, + default_timeout=None, + client_info=client_info, + ), + self.list_account_summaries: gapic_v1.method.wrap_method( + self.list_account_summaries, + default_timeout=None, + client_info=client_info, + ), + self.get_property: gapic_v1.method.wrap_method( + self.get_property, + default_timeout=None, + client_info=client_info, + ), + self.list_properties: gapic_v1.method.wrap_method( + self.list_properties, + default_timeout=None, + client_info=client_info, + ), + self.create_property: gapic_v1.method.wrap_method( + self.create_property, + default_timeout=None, + client_info=client_info, + ), + self.delete_property: gapic_v1.method.wrap_method( + self.delete_property, + default_timeout=None, + client_info=client_info, + ), + self.update_property: gapic_v1.method.wrap_method( + self.update_property, + default_timeout=None, + client_info=client_info, + ), + self.create_firebase_link: gapic_v1.method.wrap_method( + self.create_firebase_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_firebase_link: gapic_v1.method.wrap_method( + self.delete_firebase_link, + default_timeout=None, + client_info=client_info, + ), + self.list_firebase_links: gapic_v1.method.wrap_method( + self.list_firebase_links, + default_timeout=None, + client_info=client_info, + ), + self.create_google_ads_link: gapic_v1.method.wrap_method( + self.create_google_ads_link, + default_timeout=None, + client_info=client_info, + ), + self.update_google_ads_link: gapic_v1.method.wrap_method( + self.update_google_ads_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_google_ads_link: gapic_v1.method.wrap_method( + self.delete_google_ads_link, + default_timeout=None, + client_info=client_info, + ), + self.list_google_ads_links: gapic_v1.method.wrap_method( + self.list_google_ads_links, + default_timeout=None, + client_info=client_info, + ), + self.get_data_sharing_settings: gapic_v1.method.wrap_method( + self.get_data_sharing_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_measurement_protocol_secret: gapic_v1.method.wrap_method( + self.get_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_measurement_protocol_secrets: gapic_v1.method.wrap_method( + self.list_measurement_protocol_secrets, + default_timeout=None, + client_info=client_info, + ), + self.create_measurement_protocol_secret: gapic_v1.method.wrap_method( + self.create_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_measurement_protocol_secret: gapic_v1.method.wrap_method( + self.delete_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.update_measurement_protocol_secret: gapic_v1.method.wrap_method( + self.update_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.acknowledge_user_data_collection: gapic_v1.method.wrap_method( + self.acknowledge_user_data_collection, + default_timeout=None, + client_info=client_info, + ), + self.search_change_history_events: gapic_v1.method.wrap_method( + self.search_change_history_events, + default_timeout=None, + client_info=client_info, + ), + self.create_conversion_event: gapic_v1.method.wrap_method( + self.create_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.update_conversion_event: gapic_v1.method.wrap_method( + self.update_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.get_conversion_event: gapic_v1.method.wrap_method( + self.get_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversion_event: gapic_v1.method.wrap_method( + self.delete_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.list_conversion_events: gapic_v1.method.wrap_method( + self.list_conversion_events, + default_timeout=None, + client_info=client_info, + ), + self.create_key_event: gapic_v1.method.wrap_method( + self.create_key_event, + default_timeout=None, + client_info=client_info, + ), + self.update_key_event: gapic_v1.method.wrap_method( + self.update_key_event, + default_timeout=None, + client_info=client_info, + ), + self.get_key_event: gapic_v1.method.wrap_method( + self.get_key_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_key_event: gapic_v1.method.wrap_method( + self.delete_key_event, + default_timeout=None, + client_info=client_info, + ), + self.list_key_events: gapic_v1.method.wrap_method( + self.list_key_events, + default_timeout=None, + client_info=client_info, + ), + self.create_custom_dimension: gapic_v1.method.wrap_method( + self.create_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.update_custom_dimension: gapic_v1.method.wrap_method( + self.update_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.list_custom_dimensions: gapic_v1.method.wrap_method( + self.list_custom_dimensions, + default_timeout=None, + client_info=client_info, + ), + self.archive_custom_dimension: gapic_v1.method.wrap_method( + self.archive_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.get_custom_dimension: gapic_v1.method.wrap_method( + self.get_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.create_custom_metric: gapic_v1.method.wrap_method( + self.create_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.update_custom_metric: gapic_v1.method.wrap_method( + self.update_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.list_custom_metrics: gapic_v1.method.wrap_method( + self.list_custom_metrics, + default_timeout=None, + client_info=client_info, + ), + self.archive_custom_metric: gapic_v1.method.wrap_method( + self.archive_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.get_custom_metric: gapic_v1.method.wrap_method( + self.get_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.get_data_retention_settings: gapic_v1.method.wrap_method( + self.get_data_retention_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_data_retention_settings: gapic_v1.method.wrap_method( + self.update_data_retention_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_data_stream: gapic_v1.method.wrap_method( + self.create_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_stream: gapic_v1.method.wrap_method( + self.delete_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.update_data_stream: gapic_v1.method.wrap_method( + self.update_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.list_data_streams: gapic_v1.method.wrap_method( + self.list_data_streams, + default_timeout=None, + client_info=client_info, + ), + self.get_data_stream: gapic_v1.method.wrap_method( + self.get_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.run_access_report: gapic_v1.method.wrap_method( + self.run_access_report, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get_account(self) -> Callable[ + [analytics_admin.GetAccountRequest], + Union[ + resources.Account, + Awaitable[resources.Account] + ]]: + raise NotImplementedError() + + @property + def list_accounts(self) -> Callable[ + [analytics_admin.ListAccountsRequest], + Union[ + analytics_admin.ListAccountsResponse, + Awaitable[analytics_admin.ListAccountsResponse] + ]]: + raise NotImplementedError() + + @property + def delete_account(self) -> Callable[ + [analytics_admin.DeleteAccountRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_account(self) -> Callable[ + [analytics_admin.UpdateAccountRequest], + Union[ + resources.Account, + Awaitable[resources.Account] + ]]: + raise NotImplementedError() + + @property + def provision_account_ticket(self) -> Callable[ + [analytics_admin.ProvisionAccountTicketRequest], + Union[ + analytics_admin.ProvisionAccountTicketResponse, + Awaitable[analytics_admin.ProvisionAccountTicketResponse] + ]]: + raise NotImplementedError() + + @property + def list_account_summaries(self) -> Callable[ + [analytics_admin.ListAccountSummariesRequest], + Union[ + analytics_admin.ListAccountSummariesResponse, + Awaitable[analytics_admin.ListAccountSummariesResponse] + ]]: + raise NotImplementedError() + + @property + def get_property(self) -> Callable[ + [analytics_admin.GetPropertyRequest], + Union[ + resources.Property, + Awaitable[resources.Property] + ]]: + raise NotImplementedError() + + @property + def list_properties(self) -> Callable[ + [analytics_admin.ListPropertiesRequest], + Union[ + analytics_admin.ListPropertiesResponse, + Awaitable[analytics_admin.ListPropertiesResponse] + ]]: + raise NotImplementedError() + + @property + def create_property(self) -> Callable[ + [analytics_admin.CreatePropertyRequest], + Union[ + resources.Property, + Awaitable[resources.Property] + ]]: + raise NotImplementedError() + + @property + def delete_property(self) -> Callable[ + [analytics_admin.DeletePropertyRequest], + Union[ + resources.Property, + Awaitable[resources.Property] + ]]: + raise NotImplementedError() + + @property + def update_property(self) -> Callable[ + [analytics_admin.UpdatePropertyRequest], + Union[ + resources.Property, + Awaitable[resources.Property] + ]]: + raise NotImplementedError() + + @property + def create_firebase_link(self) -> Callable[ + [analytics_admin.CreateFirebaseLinkRequest], + Union[ + resources.FirebaseLink, + Awaitable[resources.FirebaseLink] + ]]: + raise NotImplementedError() + + @property + def delete_firebase_link(self) -> Callable[ + [analytics_admin.DeleteFirebaseLinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_firebase_links(self) -> Callable[ + [analytics_admin.ListFirebaseLinksRequest], + Union[ + analytics_admin.ListFirebaseLinksResponse, + Awaitable[analytics_admin.ListFirebaseLinksResponse] + ]]: + raise NotImplementedError() + + @property + def create_google_ads_link(self) -> Callable[ + [analytics_admin.CreateGoogleAdsLinkRequest], + Union[ + resources.GoogleAdsLink, + Awaitable[resources.GoogleAdsLink] + ]]: + raise NotImplementedError() + + @property + def update_google_ads_link(self) -> Callable[ + [analytics_admin.UpdateGoogleAdsLinkRequest], + Union[ + resources.GoogleAdsLink, + Awaitable[resources.GoogleAdsLink] + ]]: + raise NotImplementedError() + + @property + def delete_google_ads_link(self) -> Callable[ + [analytics_admin.DeleteGoogleAdsLinkRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_google_ads_links(self) -> Callable[ + [analytics_admin.ListGoogleAdsLinksRequest], + Union[ + analytics_admin.ListGoogleAdsLinksResponse, + Awaitable[analytics_admin.ListGoogleAdsLinksResponse] + ]]: + raise NotImplementedError() + + @property + def get_data_sharing_settings(self) -> Callable[ + [analytics_admin.GetDataSharingSettingsRequest], + Union[ + resources.DataSharingSettings, + Awaitable[resources.DataSharingSettings] + ]]: + raise NotImplementedError() + + @property + def get_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.GetMeasurementProtocolSecretRequest], + Union[ + resources.MeasurementProtocolSecret, + Awaitable[resources.MeasurementProtocolSecret] + ]]: + raise NotImplementedError() + + @property + def list_measurement_protocol_secrets(self) -> Callable[ + [analytics_admin.ListMeasurementProtocolSecretsRequest], + Union[ + analytics_admin.ListMeasurementProtocolSecretsResponse, + Awaitable[analytics_admin.ListMeasurementProtocolSecretsResponse] + ]]: + raise NotImplementedError() + + @property + def create_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.CreateMeasurementProtocolSecretRequest], + Union[ + resources.MeasurementProtocolSecret, + Awaitable[resources.MeasurementProtocolSecret] + ]]: + raise NotImplementedError() + + @property + def delete_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.DeleteMeasurementProtocolSecretRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.UpdateMeasurementProtocolSecretRequest], + Union[ + resources.MeasurementProtocolSecret, + Awaitable[resources.MeasurementProtocolSecret] + ]]: + raise NotImplementedError() + + @property + def acknowledge_user_data_collection(self) -> Callable[ + [analytics_admin.AcknowledgeUserDataCollectionRequest], + Union[ + analytics_admin.AcknowledgeUserDataCollectionResponse, + Awaitable[analytics_admin.AcknowledgeUserDataCollectionResponse] + ]]: + raise NotImplementedError() + + @property + def search_change_history_events(self) -> Callable[ + [analytics_admin.SearchChangeHistoryEventsRequest], + Union[ + analytics_admin.SearchChangeHistoryEventsResponse, + Awaitable[analytics_admin.SearchChangeHistoryEventsResponse] + ]]: + raise NotImplementedError() + + @property + def create_conversion_event(self) -> Callable[ + [analytics_admin.CreateConversionEventRequest], + Union[ + resources.ConversionEvent, + Awaitable[resources.ConversionEvent] + ]]: + raise NotImplementedError() + + @property + def update_conversion_event(self) -> Callable[ + [analytics_admin.UpdateConversionEventRequest], + Union[ + resources.ConversionEvent, + Awaitable[resources.ConversionEvent] + ]]: + raise NotImplementedError() + + @property + def get_conversion_event(self) -> Callable[ + [analytics_admin.GetConversionEventRequest], + Union[ + resources.ConversionEvent, + Awaitable[resources.ConversionEvent] + ]]: + raise NotImplementedError() + + @property + def delete_conversion_event(self) -> Callable[ + [analytics_admin.DeleteConversionEventRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_conversion_events(self) -> Callable[ + [analytics_admin.ListConversionEventsRequest], + Union[ + analytics_admin.ListConversionEventsResponse, + Awaitable[analytics_admin.ListConversionEventsResponse] + ]]: + raise NotImplementedError() + + @property + def create_key_event(self) -> Callable[ + [analytics_admin.CreateKeyEventRequest], + Union[ + resources.KeyEvent, + Awaitable[resources.KeyEvent] + ]]: + raise NotImplementedError() + + @property + def update_key_event(self) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], + Union[ + resources.KeyEvent, + Awaitable[resources.KeyEvent] + ]]: + raise NotImplementedError() + + @property + def get_key_event(self) -> Callable[ + [analytics_admin.GetKeyEventRequest], + Union[ + resources.KeyEvent, + Awaitable[resources.KeyEvent] + ]]: + raise NotImplementedError() + + @property + def delete_key_event(self) -> Callable[ + [analytics_admin.DeleteKeyEventRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_key_events(self) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + Union[ + analytics_admin.ListKeyEventsResponse, + Awaitable[analytics_admin.ListKeyEventsResponse] + ]]: + raise NotImplementedError() + + @property + def create_custom_dimension(self) -> Callable[ + [analytics_admin.CreateCustomDimensionRequest], + Union[ + resources.CustomDimension, + Awaitable[resources.CustomDimension] + ]]: + raise NotImplementedError() + + @property + def update_custom_dimension(self) -> Callable[ + [analytics_admin.UpdateCustomDimensionRequest], + Union[ + resources.CustomDimension, + Awaitable[resources.CustomDimension] + ]]: + raise NotImplementedError() + + @property + def list_custom_dimensions(self) -> Callable[ + [analytics_admin.ListCustomDimensionsRequest], + Union[ + analytics_admin.ListCustomDimensionsResponse, + Awaitable[analytics_admin.ListCustomDimensionsResponse] + ]]: + raise NotImplementedError() + + @property + def archive_custom_dimension(self) -> Callable[ + [analytics_admin.ArchiveCustomDimensionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_custom_dimension(self) -> Callable[ + [analytics_admin.GetCustomDimensionRequest], + Union[ + resources.CustomDimension, + Awaitable[resources.CustomDimension] + ]]: + raise NotImplementedError() + + @property + def create_custom_metric(self) -> Callable[ + [analytics_admin.CreateCustomMetricRequest], + Union[ + resources.CustomMetric, + Awaitable[resources.CustomMetric] + ]]: + raise NotImplementedError() + + @property + def update_custom_metric(self) -> Callable[ + [analytics_admin.UpdateCustomMetricRequest], + Union[ + resources.CustomMetric, + Awaitable[resources.CustomMetric] + ]]: + raise NotImplementedError() + + @property + def list_custom_metrics(self) -> Callable[ + [analytics_admin.ListCustomMetricsRequest], + Union[ + analytics_admin.ListCustomMetricsResponse, + Awaitable[analytics_admin.ListCustomMetricsResponse] + ]]: + raise NotImplementedError() + + @property + def archive_custom_metric(self) -> Callable[ + [analytics_admin.ArchiveCustomMetricRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def get_custom_metric(self) -> Callable[ + [analytics_admin.GetCustomMetricRequest], + Union[ + resources.CustomMetric, + Awaitable[resources.CustomMetric] + ]]: + raise NotImplementedError() + + @property + def get_data_retention_settings(self) -> Callable[ + [analytics_admin.GetDataRetentionSettingsRequest], + Union[ + resources.DataRetentionSettings, + Awaitable[resources.DataRetentionSettings] + ]]: + raise NotImplementedError() + + @property + def update_data_retention_settings(self) -> Callable[ + [analytics_admin.UpdateDataRetentionSettingsRequest], + Union[ + resources.DataRetentionSettings, + Awaitable[resources.DataRetentionSettings] + ]]: + raise NotImplementedError() + + @property + def create_data_stream(self) -> Callable[ + [analytics_admin.CreateDataStreamRequest], + Union[ + resources.DataStream, + Awaitable[resources.DataStream] + ]]: + raise NotImplementedError() + + @property + def delete_data_stream(self) -> Callable[ + [analytics_admin.DeleteDataStreamRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def update_data_stream(self) -> Callable[ + [analytics_admin.UpdateDataStreamRequest], + Union[ + resources.DataStream, + Awaitable[resources.DataStream] + ]]: + raise NotImplementedError() + + @property + def list_data_streams(self) -> Callable[ + [analytics_admin.ListDataStreamsRequest], + Union[ + analytics_admin.ListDataStreamsResponse, + Awaitable[analytics_admin.ListDataStreamsResponse] + ]]: + raise NotImplementedError() + + @property + def get_data_stream(self) -> Callable[ + [analytics_admin.GetDataStreamRequest], + Union[ + resources.DataStream, + Awaitable[resources.DataStream] + ]]: + raise NotImplementedError() + + @property + def run_access_report(self) -> Callable[ + [analytics_admin.RunAccessReportRequest], + Union[ + analytics_admin.RunAccessReportResponse, + Awaitable[analytics_admin.RunAccessReportResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AnalyticsAdminServiceTransport', +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/grpc.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/grpc.py new file mode 100644 index 000000000000..210c7544dd1d --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/grpc.py @@ -0,0 +1,1730 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1beta.types import analytics_admin +from google.analytics.admin_v1beta.types import resources +from google.protobuf import empty_pb2 # type: ignore +from .base import AnalyticsAdminServiceTransport, DEFAULT_CLIENT_INFO + + +class AnalyticsAdminServiceGrpcTransport(AnalyticsAdminServiceTransport): + """gRPC backend transport for AnalyticsAdminService. + + Service Interface for the Analytics Admin API (GA4). + + 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 = 'analyticsadmin.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'analyticsadmin.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'analyticsadmin.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 get_account(self) -> Callable[ + [analytics_admin.GetAccountRequest], + resources.Account]: + r"""Return a callable for the get account method over gRPC. + + Lookup for a single Account. + + Returns: + Callable[[~.GetAccountRequest], + ~.Account]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account' not in self._stubs: + self._stubs['get_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetAccount', + request_serializer=analytics_admin.GetAccountRequest.serialize, + response_deserializer=resources.Account.deserialize, + ) + return self._stubs['get_account'] + + @property + def list_accounts(self) -> Callable[ + [analytics_admin.ListAccountsRequest], + analytics_admin.ListAccountsResponse]: + r"""Return a callable for the list accounts method over gRPC. + + Returns all accounts accessible by the caller. + + Note that these accounts might not currently have GA4 + properties. Soft-deleted (ie: "trashed") accounts are + excluded by default. Returns an empty list if no + relevant accounts are found. + + Returns: + Callable[[~.ListAccountsRequest], + ~.ListAccountsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_accounts' not in self._stubs: + self._stubs['list_accounts'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListAccounts', + request_serializer=analytics_admin.ListAccountsRequest.serialize, + response_deserializer=analytics_admin.ListAccountsResponse.deserialize, + ) + return self._stubs['list_accounts'] + + @property + def delete_account(self) -> Callable[ + [analytics_admin.DeleteAccountRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete account method over gRPC. + + Marks target Account as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + accounts. However, they can be restored using the Trash + Can UI. + + If the accounts are not restored before the expiration + time, the account and all child resources (eg: + Properties, GoogleAdsLinks, Streams, AccessBindings) + will be permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found. + + Returns: + Callable[[~.DeleteAccountRequest], + ~.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_account' not in self._stubs: + self._stubs['delete_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteAccount', + request_serializer=analytics_admin.DeleteAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_account'] + + @property + def update_account(self) -> Callable[ + [analytics_admin.UpdateAccountRequest], + resources.Account]: + r"""Return a callable for the update account method over gRPC. + + Updates an account. + + Returns: + Callable[[~.UpdateAccountRequest], + ~.Account]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account' not in self._stubs: + self._stubs['update_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateAccount', + request_serializer=analytics_admin.UpdateAccountRequest.serialize, + response_deserializer=resources.Account.deserialize, + ) + return self._stubs['update_account'] + + @property + def provision_account_ticket(self) -> Callable[ + [analytics_admin.ProvisionAccountTicketRequest], + analytics_admin.ProvisionAccountTicketResponse]: + r"""Return a callable for the provision account ticket method over gRPC. + + Requests a ticket for creating an account. + + Returns: + Callable[[~.ProvisionAccountTicketRequest], + ~.ProvisionAccountTicketResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'provision_account_ticket' not in self._stubs: + self._stubs['provision_account_ticket'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ProvisionAccountTicket', + request_serializer=analytics_admin.ProvisionAccountTicketRequest.serialize, + response_deserializer=analytics_admin.ProvisionAccountTicketResponse.deserialize, + ) + return self._stubs['provision_account_ticket'] + + @property + def list_account_summaries(self) -> Callable[ + [analytics_admin.ListAccountSummariesRequest], + analytics_admin.ListAccountSummariesResponse]: + r"""Return a callable for the list account summaries method over gRPC. + + Returns summaries of all accounts accessible by the + caller. + + Returns: + Callable[[~.ListAccountSummariesRequest], + ~.ListAccountSummariesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account_summaries' not in self._stubs: + self._stubs['list_account_summaries'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListAccountSummaries', + request_serializer=analytics_admin.ListAccountSummariesRequest.serialize, + response_deserializer=analytics_admin.ListAccountSummariesResponse.deserialize, + ) + return self._stubs['list_account_summaries'] + + @property + def get_property(self) -> Callable[ + [analytics_admin.GetPropertyRequest], + resources.Property]: + r"""Return a callable for the get property method over gRPC. + + Lookup for a single "GA4" Property. + + Returns: + Callable[[~.GetPropertyRequest], + ~.Property]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['get_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetProperty', + request_serializer=analytics_admin.GetPropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['get_property'] + + @property + def list_properties(self) -> Callable[ + [analytics_admin.ListPropertiesRequest], + analytics_admin.ListPropertiesResponse]: + r"""Return a callable for the list properties method over gRPC. + + Returns child Properties under the specified parent + Account. + Only "GA4" properties will be returned. + Properties will be excluded if the caller does not have + access. Soft-deleted (ie: "trashed") properties are + excluded by default. Returns an empty list if no + relevant properties are found. + + Returns: + Callable[[~.ListPropertiesRequest], + ~.ListPropertiesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_properties' not in self._stubs: + self._stubs['list_properties'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListProperties', + request_serializer=analytics_admin.ListPropertiesRequest.serialize, + response_deserializer=analytics_admin.ListPropertiesResponse.deserialize, + ) + return self._stubs['list_properties'] + + @property + def create_property(self) -> Callable[ + [analytics_admin.CreatePropertyRequest], + resources.Property]: + r"""Return a callable for the create property method over gRPC. + + Creates an "GA4" property with the specified location + and attributes. + + Returns: + Callable[[~.CreatePropertyRequest], + ~.Property]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['create_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateProperty', + request_serializer=analytics_admin.CreatePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['create_property'] + + @property + def delete_property(self) -> Callable[ + [analytics_admin.DeletePropertyRequest], + resources.Property]: + r"""Return a callable for the delete property method over gRPC. + + Marks target Property as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + properties. However, they can be restored using the + Trash Can UI. + + If the properties are not restored before the expiration + time, the Property and all child resources (eg: + GoogleAdsLinks, Streams, AccessBindings) will be + permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found, or is not a + GA4 Property. + + Returns: + Callable[[~.DeletePropertyRequest], + ~.Property]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['delete_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteProperty', + request_serializer=analytics_admin.DeletePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['delete_property'] + + @property + def update_property(self) -> Callable[ + [analytics_admin.UpdatePropertyRequest], + resources.Property]: + r"""Return a callable for the update property method over gRPC. + + Updates a property. + + Returns: + Callable[[~.UpdatePropertyRequest], + ~.Property]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['update_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateProperty', + request_serializer=analytics_admin.UpdatePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['update_property'] + + @property + def create_firebase_link(self) -> Callable[ + [analytics_admin.CreateFirebaseLinkRequest], + resources.FirebaseLink]: + r"""Return a callable for the create firebase link method over gRPC. + + Creates a FirebaseLink. + + Properties can have at most one FirebaseLink. + + Returns: + Callable[[~.CreateFirebaseLinkRequest], + ~.FirebaseLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_firebase_link' not in self._stubs: + self._stubs['create_firebase_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateFirebaseLink', + request_serializer=analytics_admin.CreateFirebaseLinkRequest.serialize, + response_deserializer=resources.FirebaseLink.deserialize, + ) + return self._stubs['create_firebase_link'] + + @property + def delete_firebase_link(self) -> Callable[ + [analytics_admin.DeleteFirebaseLinkRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete firebase link method over gRPC. + + Deletes a FirebaseLink on a property + + Returns: + Callable[[~.DeleteFirebaseLinkRequest], + ~.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_firebase_link' not in self._stubs: + self._stubs['delete_firebase_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteFirebaseLink', + request_serializer=analytics_admin.DeleteFirebaseLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_firebase_link'] + + @property + def list_firebase_links(self) -> Callable[ + [analytics_admin.ListFirebaseLinksRequest], + analytics_admin.ListFirebaseLinksResponse]: + r"""Return a callable for the list firebase links method over gRPC. + + Lists FirebaseLinks on a property. + Properties can have at most one FirebaseLink. + + Returns: + Callable[[~.ListFirebaseLinksRequest], + ~.ListFirebaseLinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_firebase_links' not in self._stubs: + self._stubs['list_firebase_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListFirebaseLinks', + request_serializer=analytics_admin.ListFirebaseLinksRequest.serialize, + response_deserializer=analytics_admin.ListFirebaseLinksResponse.deserialize, + ) + return self._stubs['list_firebase_links'] + + @property + def create_google_ads_link(self) -> Callable[ + [analytics_admin.CreateGoogleAdsLinkRequest], + resources.GoogleAdsLink]: + r"""Return a callable for the create google ads link method over gRPC. + + Creates a GoogleAdsLink. + + Returns: + Callable[[~.CreateGoogleAdsLinkRequest], + ~.GoogleAdsLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_link' not in self._stubs: + self._stubs['create_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateGoogleAdsLink', + request_serializer=analytics_admin.CreateGoogleAdsLinkRequest.serialize, + response_deserializer=resources.GoogleAdsLink.deserialize, + ) + return self._stubs['create_google_ads_link'] + + @property + def update_google_ads_link(self) -> Callable[ + [analytics_admin.UpdateGoogleAdsLinkRequest], + resources.GoogleAdsLink]: + r"""Return a callable for the update google ads link method over gRPC. + + Updates a GoogleAdsLink on a property + + Returns: + Callable[[~.UpdateGoogleAdsLinkRequest], + ~.GoogleAdsLink]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_link' not in self._stubs: + self._stubs['update_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateGoogleAdsLink', + request_serializer=analytics_admin.UpdateGoogleAdsLinkRequest.serialize, + response_deserializer=resources.GoogleAdsLink.deserialize, + ) + return self._stubs['update_google_ads_link'] + + @property + def delete_google_ads_link(self) -> Callable[ + [analytics_admin.DeleteGoogleAdsLinkRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete google ads link method over gRPC. + + Deletes a GoogleAdsLink on a property + + Returns: + Callable[[~.DeleteGoogleAdsLinkRequest], + ~.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_google_ads_link' not in self._stubs: + self._stubs['delete_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteGoogleAdsLink', + request_serializer=analytics_admin.DeleteGoogleAdsLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_google_ads_link'] + + @property + def list_google_ads_links(self) -> Callable[ + [analytics_admin.ListGoogleAdsLinksRequest], + analytics_admin.ListGoogleAdsLinksResponse]: + r"""Return a callable for the list google ads links method over gRPC. + + Lists GoogleAdsLinks on a property. + + Returns: + Callable[[~.ListGoogleAdsLinksRequest], + ~.ListGoogleAdsLinksResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_links' not in self._stubs: + self._stubs['list_google_ads_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListGoogleAdsLinks', + request_serializer=analytics_admin.ListGoogleAdsLinksRequest.serialize, + response_deserializer=analytics_admin.ListGoogleAdsLinksResponse.deserialize, + ) + return self._stubs['list_google_ads_links'] + + @property + def get_data_sharing_settings(self) -> Callable[ + [analytics_admin.GetDataSharingSettingsRequest], + resources.DataSharingSettings]: + r"""Return a callable for the get data sharing settings method over gRPC. + + Get data sharing settings on an account. + Data sharing settings are singletons. + + Returns: + Callable[[~.GetDataSharingSettingsRequest], + ~.DataSharingSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_sharing_settings' not in self._stubs: + self._stubs['get_data_sharing_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetDataSharingSettings', + request_serializer=analytics_admin.GetDataSharingSettingsRequest.serialize, + response_deserializer=resources.DataSharingSettings.deserialize, + ) + return self._stubs['get_data_sharing_settings'] + + @property + def get_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.GetMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + r"""Return a callable for the get measurement protocol + secret method over gRPC. + + Lookup for a single "GA4" MeasurementProtocolSecret. + + Returns: + Callable[[~.GetMeasurementProtocolSecretRequest], + ~.MeasurementProtocolSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['get_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetMeasurementProtocolSecret', + request_serializer=analytics_admin.GetMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['get_measurement_protocol_secret'] + + @property + def list_measurement_protocol_secrets(self) -> Callable[ + [analytics_admin.ListMeasurementProtocolSecretsRequest], + analytics_admin.ListMeasurementProtocolSecretsResponse]: + r"""Return a callable for the list measurement protocol + secrets method over gRPC. + + Returns child MeasurementProtocolSecrets under the + specified parent Property. + + Returns: + Callable[[~.ListMeasurementProtocolSecretsRequest], + ~.ListMeasurementProtocolSecretsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secrets' not in self._stubs: + self._stubs['list_measurement_protocol_secrets'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListMeasurementProtocolSecrets', + request_serializer=analytics_admin.ListMeasurementProtocolSecretsRequest.serialize, + response_deserializer=analytics_admin.ListMeasurementProtocolSecretsResponse.deserialize, + ) + return self._stubs['list_measurement_protocol_secrets'] + + @property + def create_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.CreateMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + r"""Return a callable for the create measurement protocol + secret method over gRPC. + + Creates a measurement protocol secret. + + Returns: + Callable[[~.CreateMeasurementProtocolSecretRequest], + ~.MeasurementProtocolSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['create_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateMeasurementProtocolSecret', + request_serializer=analytics_admin.CreateMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['create_measurement_protocol_secret'] + + @property + def delete_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.DeleteMeasurementProtocolSecretRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete measurement protocol + secret method over gRPC. + + Deletes target MeasurementProtocolSecret. + + Returns: + Callable[[~.DeleteMeasurementProtocolSecretRequest], + ~.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_measurement_protocol_secret' not in self._stubs: + self._stubs['delete_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteMeasurementProtocolSecret', + request_serializer=analytics_admin.DeleteMeasurementProtocolSecretRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_measurement_protocol_secret'] + + @property + def update_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.UpdateMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + r"""Return a callable for the update measurement protocol + secret method over gRPC. + + Updates a measurement protocol secret. + + Returns: + Callable[[~.UpdateMeasurementProtocolSecretRequest], + ~.MeasurementProtocolSecret]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['update_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateMeasurementProtocolSecret', + request_serializer=analytics_admin.UpdateMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['update_measurement_protocol_secret'] + + @property + def acknowledge_user_data_collection(self) -> Callable[ + [analytics_admin.AcknowledgeUserDataCollectionRequest], + analytics_admin.AcknowledgeUserDataCollectionResponse]: + r"""Return a callable for the acknowledge user data + collection method over gRPC. + + Acknowledges the terms of user data collection for + the specified property. + This acknowledgement must be completed (either in the + Google Analytics UI or through this API) before + MeasurementProtocolSecret resources may be created. + + Returns: + Callable[[~.AcknowledgeUserDataCollectionRequest], + ~.AcknowledgeUserDataCollectionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acknowledge_user_data_collection' not in self._stubs: + self._stubs['acknowledge_user_data_collection'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/AcknowledgeUserDataCollection', + request_serializer=analytics_admin.AcknowledgeUserDataCollectionRequest.serialize, + response_deserializer=analytics_admin.AcknowledgeUserDataCollectionResponse.deserialize, + ) + return self._stubs['acknowledge_user_data_collection'] + + @property + def search_change_history_events(self) -> Callable[ + [analytics_admin.SearchChangeHistoryEventsRequest], + analytics_admin.SearchChangeHistoryEventsResponse]: + r"""Return a callable for the search change history events method over gRPC. + + Searches through all changes to an account or its + children given the specified set of filters. + + Returns: + Callable[[~.SearchChangeHistoryEventsRequest], + ~.SearchChangeHistoryEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_change_history_events' not in self._stubs: + self._stubs['search_change_history_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/SearchChangeHistoryEvents', + request_serializer=analytics_admin.SearchChangeHistoryEventsRequest.serialize, + response_deserializer=analytics_admin.SearchChangeHistoryEventsResponse.deserialize, + ) + return self._stubs['search_change_history_events'] + + @property + def create_conversion_event(self) -> Callable[ + [analytics_admin.CreateConversionEventRequest], + resources.ConversionEvent]: + r"""Return a callable for the create conversion event method over gRPC. + + Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. + + Returns: + Callable[[~.CreateConversionEventRequest], + ~.ConversionEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['create_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateConversionEvent', + request_serializer=analytics_admin.CreateConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['create_conversion_event'] + + @property + def update_conversion_event(self) -> Callable[ + [analytics_admin.UpdateConversionEventRequest], + resources.ConversionEvent]: + r"""Return a callable for the update conversion event method over gRPC. + + Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. + + Returns: + Callable[[~.UpdateConversionEventRequest], + ~.ConversionEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['update_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateConversionEvent', + request_serializer=analytics_admin.UpdateConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['update_conversion_event'] + + @property + def get_conversion_event(self) -> Callable[ + [analytics_admin.GetConversionEventRequest], + resources.ConversionEvent]: + r"""Return a callable for the get conversion event method over gRPC. + + Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. + + Returns: + Callable[[~.GetConversionEventRequest], + ~.ConversionEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['get_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetConversionEvent', + request_serializer=analytics_admin.GetConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['get_conversion_event'] + + @property + def delete_conversion_event(self) -> Callable[ + [analytics_admin.DeleteConversionEventRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete conversion event method over gRPC. + + Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. + + Returns: + Callable[[~.DeleteConversionEventRequest], + ~.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_conversion_event' not in self._stubs: + self._stubs['delete_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteConversionEvent', + request_serializer=analytics_admin.DeleteConversionEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversion_event'] + + @property + def list_conversion_events(self) -> Callable[ + [analytics_admin.ListConversionEventsRequest], + analytics_admin.ListConversionEventsResponse]: + r"""Return a callable for the list conversion events method over gRPC. + + Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + + Returns an empty list if no conversion events are found. + + Returns: + Callable[[~.ListConversionEventsRequest], + ~.ListConversionEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_events' not in self._stubs: + self._stubs['list_conversion_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListConversionEvents', + request_serializer=analytics_admin.ListConversionEventsRequest.serialize, + response_deserializer=analytics_admin.ListConversionEventsResponse.deserialize, + ) + return self._stubs['list_conversion_events'] + + @property + def create_key_event(self) -> Callable[ + [analytics_admin.CreateKeyEventRequest], + resources.KeyEvent]: + r"""Return a callable for the create key event method over gRPC. + + Creates a Key Event. + + Returns: + Callable[[~.CreateKeyEventRequest], + ~.KeyEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['create_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateKeyEvent', + request_serializer=analytics_admin.CreateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['create_key_event'] + + @property + def update_key_event(self) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], + resources.KeyEvent]: + r"""Return a callable for the update key event method over gRPC. + + Updates a Key Event. + + Returns: + Callable[[~.UpdateKeyEventRequest], + ~.KeyEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['update_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateKeyEvent', + request_serializer=analytics_admin.UpdateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['update_key_event'] + + @property + def get_key_event(self) -> Callable[ + [analytics_admin.GetKeyEventRequest], + resources.KeyEvent]: + r"""Return a callable for the get key event method over gRPC. + + Retrieve a single Key Event. + + Returns: + Callable[[~.GetKeyEventRequest], + ~.KeyEvent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['get_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetKeyEvent', + request_serializer=analytics_admin.GetKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['get_key_event'] + + @property + def delete_key_event(self) -> Callable[ + [analytics_admin.DeleteKeyEventRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete key event method over gRPC. + + Deletes a Key Event. + + Returns: + Callable[[~.DeleteKeyEventRequest], + ~.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_key_event' not in self._stubs: + self._stubs['delete_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteKeyEvent', + request_serializer=analytics_admin.DeleteKeyEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_key_event'] + + @property + def list_key_events(self) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + analytics_admin.ListKeyEventsResponse]: + r"""Return a callable for the list key events method over gRPC. + + Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + Returns: + Callable[[~.ListKeyEventsRequest], + ~.ListKeyEventsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_events' not in self._stubs: + self._stubs['list_key_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListKeyEvents', + request_serializer=analytics_admin.ListKeyEventsRequest.serialize, + response_deserializer=analytics_admin.ListKeyEventsResponse.deserialize, + ) + return self._stubs['list_key_events'] + + @property + def create_custom_dimension(self) -> Callable[ + [analytics_admin.CreateCustomDimensionRequest], + resources.CustomDimension]: + r"""Return a callable for the create custom dimension method over gRPC. + + Creates a CustomDimension. + + Returns: + Callable[[~.CreateCustomDimensionRequest], + ~.CustomDimension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['create_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateCustomDimension', + request_serializer=analytics_admin.CreateCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['create_custom_dimension'] + + @property + def update_custom_dimension(self) -> Callable[ + [analytics_admin.UpdateCustomDimensionRequest], + resources.CustomDimension]: + r"""Return a callable for the update custom dimension method over gRPC. + + Updates a CustomDimension on a property. + + Returns: + Callable[[~.UpdateCustomDimensionRequest], + ~.CustomDimension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['update_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateCustomDimension', + request_serializer=analytics_admin.UpdateCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['update_custom_dimension'] + + @property + def list_custom_dimensions(self) -> Callable[ + [analytics_admin.ListCustomDimensionsRequest], + analytics_admin.ListCustomDimensionsResponse]: + r"""Return a callable for the list custom dimensions method over gRPC. + + Lists CustomDimensions on a property. + + Returns: + Callable[[~.ListCustomDimensionsRequest], + ~.ListCustomDimensionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimensions' not in self._stubs: + self._stubs['list_custom_dimensions'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListCustomDimensions', + request_serializer=analytics_admin.ListCustomDimensionsRequest.serialize, + response_deserializer=analytics_admin.ListCustomDimensionsResponse.deserialize, + ) + return self._stubs['list_custom_dimensions'] + + @property + def archive_custom_dimension(self) -> Callable[ + [analytics_admin.ArchiveCustomDimensionRequest], + empty_pb2.Empty]: + r"""Return a callable for the archive custom dimension method over gRPC. + + Archives a CustomDimension on a property. + + Returns: + Callable[[~.ArchiveCustomDimensionRequest], + ~.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 'archive_custom_dimension' not in self._stubs: + self._stubs['archive_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ArchiveCustomDimension', + request_serializer=analytics_admin.ArchiveCustomDimensionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_custom_dimension'] + + @property + def get_custom_dimension(self) -> Callable[ + [analytics_admin.GetCustomDimensionRequest], + resources.CustomDimension]: + r"""Return a callable for the get custom dimension method over gRPC. + + Lookup for a single CustomDimension. + + Returns: + Callable[[~.GetCustomDimensionRequest], + ~.CustomDimension]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['get_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetCustomDimension', + request_serializer=analytics_admin.GetCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['get_custom_dimension'] + + @property + def create_custom_metric(self) -> Callable[ + [analytics_admin.CreateCustomMetricRequest], + resources.CustomMetric]: + r"""Return a callable for the create custom metric method over gRPC. + + Creates a CustomMetric. + + Returns: + Callable[[~.CreateCustomMetricRequest], + ~.CustomMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['create_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateCustomMetric', + request_serializer=analytics_admin.CreateCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['create_custom_metric'] + + @property + def update_custom_metric(self) -> Callable[ + [analytics_admin.UpdateCustomMetricRequest], + resources.CustomMetric]: + r"""Return a callable for the update custom metric method over gRPC. + + Updates a CustomMetric on a property. + + Returns: + Callable[[~.UpdateCustomMetricRequest], + ~.CustomMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['update_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateCustomMetric', + request_serializer=analytics_admin.UpdateCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['update_custom_metric'] + + @property + def list_custom_metrics(self) -> Callable[ + [analytics_admin.ListCustomMetricsRequest], + analytics_admin.ListCustomMetricsResponse]: + r"""Return a callable for the list custom metrics method over gRPC. + + Lists CustomMetrics on a property. + + Returns: + Callable[[~.ListCustomMetricsRequest], + ~.ListCustomMetricsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metrics' not in self._stubs: + self._stubs['list_custom_metrics'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListCustomMetrics', + request_serializer=analytics_admin.ListCustomMetricsRequest.serialize, + response_deserializer=analytics_admin.ListCustomMetricsResponse.deserialize, + ) + return self._stubs['list_custom_metrics'] + + @property + def archive_custom_metric(self) -> Callable[ + [analytics_admin.ArchiveCustomMetricRequest], + empty_pb2.Empty]: + r"""Return a callable for the archive custom metric method over gRPC. + + Archives a CustomMetric on a property. + + Returns: + Callable[[~.ArchiveCustomMetricRequest], + ~.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 'archive_custom_metric' not in self._stubs: + self._stubs['archive_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ArchiveCustomMetric', + request_serializer=analytics_admin.ArchiveCustomMetricRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_custom_metric'] + + @property + def get_custom_metric(self) -> Callable[ + [analytics_admin.GetCustomMetricRequest], + resources.CustomMetric]: + r"""Return a callable for the get custom metric method over gRPC. + + Lookup for a single CustomMetric. + + Returns: + Callable[[~.GetCustomMetricRequest], + ~.CustomMetric]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['get_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetCustomMetric', + request_serializer=analytics_admin.GetCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['get_custom_metric'] + + @property + def get_data_retention_settings(self) -> Callable[ + [analytics_admin.GetDataRetentionSettingsRequest], + resources.DataRetentionSettings]: + r"""Return a callable for the get data retention settings method over gRPC. + + Returns the singleton data retention settings for + this property. + + Returns: + Callable[[~.GetDataRetentionSettingsRequest], + ~.DataRetentionSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_retention_settings' not in self._stubs: + self._stubs['get_data_retention_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetDataRetentionSettings', + request_serializer=analytics_admin.GetDataRetentionSettingsRequest.serialize, + response_deserializer=resources.DataRetentionSettings.deserialize, + ) + return self._stubs['get_data_retention_settings'] + + @property + def update_data_retention_settings(self) -> Callable[ + [analytics_admin.UpdateDataRetentionSettingsRequest], + resources.DataRetentionSettings]: + r"""Return a callable for the update data retention settings method over gRPC. + + Updates the singleton data retention settings for + this property. + + Returns: + Callable[[~.UpdateDataRetentionSettingsRequest], + ~.DataRetentionSettings]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_retention_settings' not in self._stubs: + self._stubs['update_data_retention_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateDataRetentionSettings', + request_serializer=analytics_admin.UpdateDataRetentionSettingsRequest.serialize, + response_deserializer=resources.DataRetentionSettings.deserialize, + ) + return self._stubs['update_data_retention_settings'] + + @property + def create_data_stream(self) -> Callable[ + [analytics_admin.CreateDataStreamRequest], + resources.DataStream]: + r"""Return a callable for the create data stream method over gRPC. + + Creates a DataStream. + + Returns: + Callable[[~.CreateDataStreamRequest], + ~.DataStream]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_data_stream' not in self._stubs: + self._stubs['create_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateDataStream', + request_serializer=analytics_admin.CreateDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['create_data_stream'] + + @property + def delete_data_stream(self) -> Callable[ + [analytics_admin.DeleteDataStreamRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete data stream method over gRPC. + + Deletes a DataStream on a property. + + Returns: + Callable[[~.DeleteDataStreamRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_data_stream' not in self._stubs: + self._stubs['delete_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteDataStream', + request_serializer=analytics_admin.DeleteDataStreamRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_stream'] + + @property + def update_data_stream(self) -> Callable[ + [analytics_admin.UpdateDataStreamRequest], + resources.DataStream]: + r"""Return a callable for the update data stream method over gRPC. + + Updates a DataStream on a property. + + Returns: + Callable[[~.UpdateDataStreamRequest], + ~.DataStream]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_stream' not in self._stubs: + self._stubs['update_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateDataStream', + request_serializer=analytics_admin.UpdateDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['update_data_stream'] + + @property + def list_data_streams(self) -> Callable[ + [analytics_admin.ListDataStreamsRequest], + analytics_admin.ListDataStreamsResponse]: + r"""Return a callable for the list data streams method over gRPC. + + Lists DataStreams on a property. + + Returns: + Callable[[~.ListDataStreamsRequest], + ~.ListDataStreamsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_data_streams' not in self._stubs: + self._stubs['list_data_streams'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListDataStreams', + request_serializer=analytics_admin.ListDataStreamsRequest.serialize, + response_deserializer=analytics_admin.ListDataStreamsResponse.deserialize, + ) + return self._stubs['list_data_streams'] + + @property + def get_data_stream(self) -> Callable[ + [analytics_admin.GetDataStreamRequest], + resources.DataStream]: + r"""Return a callable for the get data stream method over gRPC. + + Lookup for a single DataStream. + + Returns: + Callable[[~.GetDataStreamRequest], + ~.DataStream]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_stream' not in self._stubs: + self._stubs['get_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetDataStream', + request_serializer=analytics_admin.GetDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['get_data_stream'] + + @property + def run_access_report(self) -> Callable[ + [analytics_admin.RunAccessReportRequest], + analytics_admin.RunAccessReportResponse]: + r"""Return a callable for the run access report method over gRPC. + + Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. + + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. + + Returns: + Callable[[~.RunAccessReportRequest], + ~.RunAccessReportResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_access_report' not in self._stubs: + self._stubs['run_access_report'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/RunAccessReport', + request_serializer=analytics_admin.RunAccessReportRequest.serialize, + response_deserializer=analytics_admin.RunAccessReportResponse.deserialize, + ) + return self._stubs['run_access_report'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AnalyticsAdminServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/grpc_asyncio.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..2e8d70ba6db1 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/grpc_asyncio.py @@ -0,0 +1,2005 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.analytics.admin_v1beta.types import analytics_admin +from google.analytics.admin_v1beta.types import resources +from google.protobuf import empty_pb2 # type: ignore +from .base import AnalyticsAdminServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AnalyticsAdminServiceGrpcTransport + + +class AnalyticsAdminServiceGrpcAsyncIOTransport(AnalyticsAdminServiceTransport): + """gRPC AsyncIO backend transport for AnalyticsAdminService. + + Service Interface for the Analytics Admin API (GA4). + + 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 = 'analyticsadmin.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'analyticsadmin.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'analyticsadmin.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def get_account(self) -> Callable[ + [analytics_admin.GetAccountRequest], + Awaitable[resources.Account]]: + r"""Return a callable for the get account method over gRPC. + + Lookup for a single Account. + + Returns: + Callable[[~.GetAccountRequest], + Awaitable[~.Account]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account' not in self._stubs: + self._stubs['get_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetAccount', + request_serializer=analytics_admin.GetAccountRequest.serialize, + response_deserializer=resources.Account.deserialize, + ) + return self._stubs['get_account'] + + @property + def list_accounts(self) -> Callable[ + [analytics_admin.ListAccountsRequest], + Awaitable[analytics_admin.ListAccountsResponse]]: + r"""Return a callable for the list accounts method over gRPC. + + Returns all accounts accessible by the caller. + + Note that these accounts might not currently have GA4 + properties. Soft-deleted (ie: "trashed") accounts are + excluded by default. Returns an empty list if no + relevant accounts are found. + + Returns: + Callable[[~.ListAccountsRequest], + Awaitable[~.ListAccountsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_accounts' not in self._stubs: + self._stubs['list_accounts'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListAccounts', + request_serializer=analytics_admin.ListAccountsRequest.serialize, + response_deserializer=analytics_admin.ListAccountsResponse.deserialize, + ) + return self._stubs['list_accounts'] + + @property + def delete_account(self) -> Callable[ + [analytics_admin.DeleteAccountRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete account method over gRPC. + + Marks target Account as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + accounts. However, they can be restored using the Trash + Can UI. + + If the accounts are not restored before the expiration + time, the account and all child resources (eg: + Properties, GoogleAdsLinks, Streams, AccessBindings) + will be permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found. + + Returns: + Callable[[~.DeleteAccountRequest], + 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_account' not in self._stubs: + self._stubs['delete_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteAccount', + request_serializer=analytics_admin.DeleteAccountRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_account'] + + @property + def update_account(self) -> Callable[ + [analytics_admin.UpdateAccountRequest], + Awaitable[resources.Account]]: + r"""Return a callable for the update account method over gRPC. + + Updates an account. + + Returns: + Callable[[~.UpdateAccountRequest], + Awaitable[~.Account]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account' not in self._stubs: + self._stubs['update_account'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateAccount', + request_serializer=analytics_admin.UpdateAccountRequest.serialize, + response_deserializer=resources.Account.deserialize, + ) + return self._stubs['update_account'] + + @property + def provision_account_ticket(self) -> Callable[ + [analytics_admin.ProvisionAccountTicketRequest], + Awaitable[analytics_admin.ProvisionAccountTicketResponse]]: + r"""Return a callable for the provision account ticket method over gRPC. + + Requests a ticket for creating an account. + + Returns: + Callable[[~.ProvisionAccountTicketRequest], + Awaitable[~.ProvisionAccountTicketResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'provision_account_ticket' not in self._stubs: + self._stubs['provision_account_ticket'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ProvisionAccountTicket', + request_serializer=analytics_admin.ProvisionAccountTicketRequest.serialize, + response_deserializer=analytics_admin.ProvisionAccountTicketResponse.deserialize, + ) + return self._stubs['provision_account_ticket'] + + @property + def list_account_summaries(self) -> Callable[ + [analytics_admin.ListAccountSummariesRequest], + Awaitable[analytics_admin.ListAccountSummariesResponse]]: + r"""Return a callable for the list account summaries method over gRPC. + + Returns summaries of all accounts accessible by the + caller. + + Returns: + Callable[[~.ListAccountSummariesRequest], + Awaitable[~.ListAccountSummariesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_account_summaries' not in self._stubs: + self._stubs['list_account_summaries'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListAccountSummaries', + request_serializer=analytics_admin.ListAccountSummariesRequest.serialize, + response_deserializer=analytics_admin.ListAccountSummariesResponse.deserialize, + ) + return self._stubs['list_account_summaries'] + + @property + def get_property(self) -> Callable[ + [analytics_admin.GetPropertyRequest], + Awaitable[resources.Property]]: + r"""Return a callable for the get property method over gRPC. + + Lookup for a single "GA4" Property. + + Returns: + Callable[[~.GetPropertyRequest], + Awaitable[~.Property]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['get_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetProperty', + request_serializer=analytics_admin.GetPropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['get_property'] + + @property + def list_properties(self) -> Callable[ + [analytics_admin.ListPropertiesRequest], + Awaitable[analytics_admin.ListPropertiesResponse]]: + r"""Return a callable for the list properties method over gRPC. + + Returns child Properties under the specified parent + Account. + Only "GA4" properties will be returned. + Properties will be excluded if the caller does not have + access. Soft-deleted (ie: "trashed") properties are + excluded by default. Returns an empty list if no + relevant properties are found. + + Returns: + Callable[[~.ListPropertiesRequest], + Awaitable[~.ListPropertiesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_properties' not in self._stubs: + self._stubs['list_properties'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListProperties', + request_serializer=analytics_admin.ListPropertiesRequest.serialize, + response_deserializer=analytics_admin.ListPropertiesResponse.deserialize, + ) + return self._stubs['list_properties'] + + @property + def create_property(self) -> Callable[ + [analytics_admin.CreatePropertyRequest], + Awaitable[resources.Property]]: + r"""Return a callable for the create property method over gRPC. + + Creates an "GA4" property with the specified location + and attributes. + + Returns: + Callable[[~.CreatePropertyRequest], + Awaitable[~.Property]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['create_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateProperty', + request_serializer=analytics_admin.CreatePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['create_property'] + + @property + def delete_property(self) -> Callable[ + [analytics_admin.DeletePropertyRequest], + Awaitable[resources.Property]]: + r"""Return a callable for the delete property method over gRPC. + + Marks target Property as soft-deleted (ie: "trashed") + and returns it. + This API does not have a method to restore soft-deleted + properties. However, they can be restored using the + Trash Can UI. + + If the properties are not restored before the expiration + time, the Property and all child resources (eg: + GoogleAdsLinks, Streams, AccessBindings) will be + permanently purged. + https://support.google.com/analytics/answer/6154772 + + Returns an error if the target is not found, or is not a + GA4 Property. + + Returns: + Callable[[~.DeletePropertyRequest], + Awaitable[~.Property]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['delete_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteProperty', + request_serializer=analytics_admin.DeletePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['delete_property'] + + @property + def update_property(self) -> Callable[ + [analytics_admin.UpdatePropertyRequest], + Awaitable[resources.Property]]: + r"""Return a callable for the update property method over gRPC. + + Updates a property. + + Returns: + Callable[[~.UpdatePropertyRequest], + Awaitable[~.Property]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_property' not in self._stubs: + self._stubs['update_property'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateProperty', + request_serializer=analytics_admin.UpdatePropertyRequest.serialize, + response_deserializer=resources.Property.deserialize, + ) + return self._stubs['update_property'] + + @property + def create_firebase_link(self) -> Callable[ + [analytics_admin.CreateFirebaseLinkRequest], + Awaitable[resources.FirebaseLink]]: + r"""Return a callable for the create firebase link method over gRPC. + + Creates a FirebaseLink. + + Properties can have at most one FirebaseLink. + + Returns: + Callable[[~.CreateFirebaseLinkRequest], + Awaitable[~.FirebaseLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_firebase_link' not in self._stubs: + self._stubs['create_firebase_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateFirebaseLink', + request_serializer=analytics_admin.CreateFirebaseLinkRequest.serialize, + response_deserializer=resources.FirebaseLink.deserialize, + ) + return self._stubs['create_firebase_link'] + + @property + def delete_firebase_link(self) -> Callable[ + [analytics_admin.DeleteFirebaseLinkRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete firebase link method over gRPC. + + Deletes a FirebaseLink on a property + + Returns: + Callable[[~.DeleteFirebaseLinkRequest], + 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_firebase_link' not in self._stubs: + self._stubs['delete_firebase_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteFirebaseLink', + request_serializer=analytics_admin.DeleteFirebaseLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_firebase_link'] + + @property + def list_firebase_links(self) -> Callable[ + [analytics_admin.ListFirebaseLinksRequest], + Awaitable[analytics_admin.ListFirebaseLinksResponse]]: + r"""Return a callable for the list firebase links method over gRPC. + + Lists FirebaseLinks on a property. + Properties can have at most one FirebaseLink. + + Returns: + Callable[[~.ListFirebaseLinksRequest], + Awaitable[~.ListFirebaseLinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_firebase_links' not in self._stubs: + self._stubs['list_firebase_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListFirebaseLinks', + request_serializer=analytics_admin.ListFirebaseLinksRequest.serialize, + response_deserializer=analytics_admin.ListFirebaseLinksResponse.deserialize, + ) + return self._stubs['list_firebase_links'] + + @property + def create_google_ads_link(self) -> Callable[ + [analytics_admin.CreateGoogleAdsLinkRequest], + Awaitable[resources.GoogleAdsLink]]: + r"""Return a callable for the create google ads link method over gRPC. + + Creates a GoogleAdsLink. + + Returns: + Callable[[~.CreateGoogleAdsLinkRequest], + Awaitable[~.GoogleAdsLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_link' not in self._stubs: + self._stubs['create_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateGoogleAdsLink', + request_serializer=analytics_admin.CreateGoogleAdsLinkRequest.serialize, + response_deserializer=resources.GoogleAdsLink.deserialize, + ) + return self._stubs['create_google_ads_link'] + + @property + def update_google_ads_link(self) -> Callable[ + [analytics_admin.UpdateGoogleAdsLinkRequest], + Awaitable[resources.GoogleAdsLink]]: + r"""Return a callable for the update google ads link method over gRPC. + + Updates a GoogleAdsLink on a property + + Returns: + Callable[[~.UpdateGoogleAdsLinkRequest], + Awaitable[~.GoogleAdsLink]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_link' not in self._stubs: + self._stubs['update_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateGoogleAdsLink', + request_serializer=analytics_admin.UpdateGoogleAdsLinkRequest.serialize, + response_deserializer=resources.GoogleAdsLink.deserialize, + ) + return self._stubs['update_google_ads_link'] + + @property + def delete_google_ads_link(self) -> Callable[ + [analytics_admin.DeleteGoogleAdsLinkRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete google ads link method over gRPC. + + Deletes a GoogleAdsLink on a property + + Returns: + Callable[[~.DeleteGoogleAdsLinkRequest], + 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_google_ads_link' not in self._stubs: + self._stubs['delete_google_ads_link'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteGoogleAdsLink', + request_serializer=analytics_admin.DeleteGoogleAdsLinkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_google_ads_link'] + + @property + def list_google_ads_links(self) -> Callable[ + [analytics_admin.ListGoogleAdsLinksRequest], + Awaitable[analytics_admin.ListGoogleAdsLinksResponse]]: + r"""Return a callable for the list google ads links method over gRPC. + + Lists GoogleAdsLinks on a property. + + Returns: + Callable[[~.ListGoogleAdsLinksRequest], + Awaitable[~.ListGoogleAdsLinksResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_google_ads_links' not in self._stubs: + self._stubs['list_google_ads_links'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListGoogleAdsLinks', + request_serializer=analytics_admin.ListGoogleAdsLinksRequest.serialize, + response_deserializer=analytics_admin.ListGoogleAdsLinksResponse.deserialize, + ) + return self._stubs['list_google_ads_links'] + + @property + def get_data_sharing_settings(self) -> Callable[ + [analytics_admin.GetDataSharingSettingsRequest], + Awaitable[resources.DataSharingSettings]]: + r"""Return a callable for the get data sharing settings method over gRPC. + + Get data sharing settings on an account. + Data sharing settings are singletons. + + Returns: + Callable[[~.GetDataSharingSettingsRequest], + Awaitable[~.DataSharingSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_sharing_settings' not in self._stubs: + self._stubs['get_data_sharing_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetDataSharingSettings', + request_serializer=analytics_admin.GetDataSharingSettingsRequest.serialize, + response_deserializer=resources.DataSharingSettings.deserialize, + ) + return self._stubs['get_data_sharing_settings'] + + @property + def get_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.GetMeasurementProtocolSecretRequest], + Awaitable[resources.MeasurementProtocolSecret]]: + r"""Return a callable for the get measurement protocol + secret method over gRPC. + + Lookup for a single "GA4" MeasurementProtocolSecret. + + Returns: + Callable[[~.GetMeasurementProtocolSecretRequest], + Awaitable[~.MeasurementProtocolSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['get_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetMeasurementProtocolSecret', + request_serializer=analytics_admin.GetMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['get_measurement_protocol_secret'] + + @property + def list_measurement_protocol_secrets(self) -> Callable[ + [analytics_admin.ListMeasurementProtocolSecretsRequest], + Awaitable[analytics_admin.ListMeasurementProtocolSecretsResponse]]: + r"""Return a callable for the list measurement protocol + secrets method over gRPC. + + Returns child MeasurementProtocolSecrets under the + specified parent Property. + + Returns: + Callable[[~.ListMeasurementProtocolSecretsRequest], + Awaitable[~.ListMeasurementProtocolSecretsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secrets' not in self._stubs: + self._stubs['list_measurement_protocol_secrets'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListMeasurementProtocolSecrets', + request_serializer=analytics_admin.ListMeasurementProtocolSecretsRequest.serialize, + response_deserializer=analytics_admin.ListMeasurementProtocolSecretsResponse.deserialize, + ) + return self._stubs['list_measurement_protocol_secrets'] + + @property + def create_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.CreateMeasurementProtocolSecretRequest], + Awaitable[resources.MeasurementProtocolSecret]]: + r"""Return a callable for the create measurement protocol + secret method over gRPC. + + Creates a measurement protocol secret. + + Returns: + Callable[[~.CreateMeasurementProtocolSecretRequest], + Awaitable[~.MeasurementProtocolSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['create_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateMeasurementProtocolSecret', + request_serializer=analytics_admin.CreateMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['create_measurement_protocol_secret'] + + @property + def delete_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.DeleteMeasurementProtocolSecretRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete measurement protocol + secret method over gRPC. + + Deletes target MeasurementProtocolSecret. + + Returns: + Callable[[~.DeleteMeasurementProtocolSecretRequest], + 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_measurement_protocol_secret' not in self._stubs: + self._stubs['delete_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteMeasurementProtocolSecret', + request_serializer=analytics_admin.DeleteMeasurementProtocolSecretRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_measurement_protocol_secret'] + + @property + def update_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.UpdateMeasurementProtocolSecretRequest], + Awaitable[resources.MeasurementProtocolSecret]]: + r"""Return a callable for the update measurement protocol + secret method over gRPC. + + Updates a measurement protocol secret. + + Returns: + Callable[[~.UpdateMeasurementProtocolSecretRequest], + Awaitable[~.MeasurementProtocolSecret]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_measurement_protocol_secret' not in self._stubs: + self._stubs['update_measurement_protocol_secret'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateMeasurementProtocolSecret', + request_serializer=analytics_admin.UpdateMeasurementProtocolSecretRequest.serialize, + response_deserializer=resources.MeasurementProtocolSecret.deserialize, + ) + return self._stubs['update_measurement_protocol_secret'] + + @property + def acknowledge_user_data_collection(self) -> Callable[ + [analytics_admin.AcknowledgeUserDataCollectionRequest], + Awaitable[analytics_admin.AcknowledgeUserDataCollectionResponse]]: + r"""Return a callable for the acknowledge user data + collection method over gRPC. + + Acknowledges the terms of user data collection for + the specified property. + This acknowledgement must be completed (either in the + Google Analytics UI or through this API) before + MeasurementProtocolSecret resources may be created. + + Returns: + Callable[[~.AcknowledgeUserDataCollectionRequest], + Awaitable[~.AcknowledgeUserDataCollectionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'acknowledge_user_data_collection' not in self._stubs: + self._stubs['acknowledge_user_data_collection'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/AcknowledgeUserDataCollection', + request_serializer=analytics_admin.AcknowledgeUserDataCollectionRequest.serialize, + response_deserializer=analytics_admin.AcknowledgeUserDataCollectionResponse.deserialize, + ) + return self._stubs['acknowledge_user_data_collection'] + + @property + def search_change_history_events(self) -> Callable[ + [analytics_admin.SearchChangeHistoryEventsRequest], + Awaitable[analytics_admin.SearchChangeHistoryEventsResponse]]: + r"""Return a callable for the search change history events method over gRPC. + + Searches through all changes to an account or its + children given the specified set of filters. + + Returns: + Callable[[~.SearchChangeHistoryEventsRequest], + Awaitable[~.SearchChangeHistoryEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'search_change_history_events' not in self._stubs: + self._stubs['search_change_history_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/SearchChangeHistoryEvents', + request_serializer=analytics_admin.SearchChangeHistoryEventsRequest.serialize, + response_deserializer=analytics_admin.SearchChangeHistoryEventsResponse.deserialize, + ) + return self._stubs['search_change_history_events'] + + @property + def create_conversion_event(self) -> Callable[ + [analytics_admin.CreateConversionEventRequest], + Awaitable[resources.ConversionEvent]]: + r"""Return a callable for the create conversion event method over gRPC. + + Deprecated: Use ``CreateKeyEvent`` instead. Creates a conversion + event with the specified attributes. + + Returns: + Callable[[~.CreateConversionEventRequest], + Awaitable[~.ConversionEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['create_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateConversionEvent', + request_serializer=analytics_admin.CreateConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['create_conversion_event'] + + @property + def update_conversion_event(self) -> Callable[ + [analytics_admin.UpdateConversionEventRequest], + Awaitable[resources.ConversionEvent]]: + r"""Return a callable for the update conversion event method over gRPC. + + Deprecated: Use ``UpdateKeyEvent`` instead. Updates a conversion + event with the specified attributes. + + Returns: + Callable[[~.UpdateConversionEventRequest], + Awaitable[~.ConversionEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['update_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateConversionEvent', + request_serializer=analytics_admin.UpdateConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['update_conversion_event'] + + @property + def get_conversion_event(self) -> Callable[ + [analytics_admin.GetConversionEventRequest], + Awaitable[resources.ConversionEvent]]: + r"""Return a callable for the get conversion event method over gRPC. + + Deprecated: Use ``GetKeyEvent`` instead. Retrieve a single + conversion event. + + Returns: + Callable[[~.GetConversionEventRequest], + Awaitable[~.ConversionEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_event' not in self._stubs: + self._stubs['get_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetConversionEvent', + request_serializer=analytics_admin.GetConversionEventRequest.serialize, + response_deserializer=resources.ConversionEvent.deserialize, + ) + return self._stubs['get_conversion_event'] + + @property + def delete_conversion_event(self) -> Callable[ + [analytics_admin.DeleteConversionEventRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete conversion event method over gRPC. + + Deprecated: Use ``DeleteKeyEvent`` instead. Deletes a conversion + event in a property. + + Returns: + Callable[[~.DeleteConversionEventRequest], + 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_conversion_event' not in self._stubs: + self._stubs['delete_conversion_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteConversionEvent', + request_serializer=analytics_admin.DeleteConversionEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_conversion_event'] + + @property + def list_conversion_events(self) -> Callable[ + [analytics_admin.ListConversionEventsRequest], + Awaitable[analytics_admin.ListConversionEventsResponse]]: + r"""Return a callable for the list conversion events method over gRPC. + + Deprecated: Use ``ListKeyEvents`` instead. Returns a list of + conversion events in the specified parent property. + + Returns an empty list if no conversion events are found. + + Returns: + Callable[[~.ListConversionEventsRequest], + Awaitable[~.ListConversionEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_conversion_events' not in self._stubs: + self._stubs['list_conversion_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListConversionEvents', + request_serializer=analytics_admin.ListConversionEventsRequest.serialize, + response_deserializer=analytics_admin.ListConversionEventsResponse.deserialize, + ) + return self._stubs['list_conversion_events'] + + @property + def create_key_event(self) -> Callable[ + [analytics_admin.CreateKeyEventRequest], + Awaitable[resources.KeyEvent]]: + r"""Return a callable for the create key event method over gRPC. + + Creates a Key Event. + + Returns: + Callable[[~.CreateKeyEventRequest], + Awaitable[~.KeyEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['create_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateKeyEvent', + request_serializer=analytics_admin.CreateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['create_key_event'] + + @property + def update_key_event(self) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], + Awaitable[resources.KeyEvent]]: + r"""Return a callable for the update key event method over gRPC. + + Updates a Key Event. + + Returns: + Callable[[~.UpdateKeyEventRequest], + Awaitable[~.KeyEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['update_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateKeyEvent', + request_serializer=analytics_admin.UpdateKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['update_key_event'] + + @property + def get_key_event(self) -> Callable[ + [analytics_admin.GetKeyEventRequest], + Awaitable[resources.KeyEvent]]: + r"""Return a callable for the get key event method over gRPC. + + Retrieve a single Key Event. + + Returns: + Callable[[~.GetKeyEventRequest], + Awaitable[~.KeyEvent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_event' not in self._stubs: + self._stubs['get_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetKeyEvent', + request_serializer=analytics_admin.GetKeyEventRequest.serialize, + response_deserializer=resources.KeyEvent.deserialize, + ) + return self._stubs['get_key_event'] + + @property + def delete_key_event(self) -> Callable[ + [analytics_admin.DeleteKeyEventRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete key event method over gRPC. + + Deletes a Key Event. + + Returns: + Callable[[~.DeleteKeyEventRequest], + 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_key_event' not in self._stubs: + self._stubs['delete_key_event'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteKeyEvent', + request_serializer=analytics_admin.DeleteKeyEventRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_key_event'] + + @property + def list_key_events(self) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + Awaitable[analytics_admin.ListKeyEventsResponse]]: + r"""Return a callable for the list key events method over gRPC. + + Returns a list of Key Events in the specified parent + property. Returns an empty list if no Key Events are + found. + + Returns: + Callable[[~.ListKeyEventsRequest], + Awaitable[~.ListKeyEventsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_events' not in self._stubs: + self._stubs['list_key_events'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListKeyEvents', + request_serializer=analytics_admin.ListKeyEventsRequest.serialize, + response_deserializer=analytics_admin.ListKeyEventsResponse.deserialize, + ) + return self._stubs['list_key_events'] + + @property + def create_custom_dimension(self) -> Callable[ + [analytics_admin.CreateCustomDimensionRequest], + Awaitable[resources.CustomDimension]]: + r"""Return a callable for the create custom dimension method over gRPC. + + Creates a CustomDimension. + + Returns: + Callable[[~.CreateCustomDimensionRequest], + Awaitable[~.CustomDimension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['create_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateCustomDimension', + request_serializer=analytics_admin.CreateCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['create_custom_dimension'] + + @property + def update_custom_dimension(self) -> Callable[ + [analytics_admin.UpdateCustomDimensionRequest], + Awaitable[resources.CustomDimension]]: + r"""Return a callable for the update custom dimension method over gRPC. + + Updates a CustomDimension on a property. + + Returns: + Callable[[~.UpdateCustomDimensionRequest], + Awaitable[~.CustomDimension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['update_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateCustomDimension', + request_serializer=analytics_admin.UpdateCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['update_custom_dimension'] + + @property + def list_custom_dimensions(self) -> Callable[ + [analytics_admin.ListCustomDimensionsRequest], + Awaitable[analytics_admin.ListCustomDimensionsResponse]]: + r"""Return a callable for the list custom dimensions method over gRPC. + + Lists CustomDimensions on a property. + + Returns: + Callable[[~.ListCustomDimensionsRequest], + Awaitable[~.ListCustomDimensionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimensions' not in self._stubs: + self._stubs['list_custom_dimensions'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListCustomDimensions', + request_serializer=analytics_admin.ListCustomDimensionsRequest.serialize, + response_deserializer=analytics_admin.ListCustomDimensionsResponse.deserialize, + ) + return self._stubs['list_custom_dimensions'] + + @property + def archive_custom_dimension(self) -> Callable[ + [analytics_admin.ArchiveCustomDimensionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the archive custom dimension method over gRPC. + + Archives a CustomDimension on a property. + + Returns: + Callable[[~.ArchiveCustomDimensionRequest], + 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 'archive_custom_dimension' not in self._stubs: + self._stubs['archive_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ArchiveCustomDimension', + request_serializer=analytics_admin.ArchiveCustomDimensionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_custom_dimension'] + + @property + def get_custom_dimension(self) -> Callable[ + [analytics_admin.GetCustomDimensionRequest], + Awaitable[resources.CustomDimension]]: + r"""Return a callable for the get custom dimension method over gRPC. + + Lookup for a single CustomDimension. + + Returns: + Callable[[~.GetCustomDimensionRequest], + Awaitable[~.CustomDimension]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_dimension' not in self._stubs: + self._stubs['get_custom_dimension'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetCustomDimension', + request_serializer=analytics_admin.GetCustomDimensionRequest.serialize, + response_deserializer=resources.CustomDimension.deserialize, + ) + return self._stubs['get_custom_dimension'] + + @property + def create_custom_metric(self) -> Callable[ + [analytics_admin.CreateCustomMetricRequest], + Awaitable[resources.CustomMetric]]: + r"""Return a callable for the create custom metric method over gRPC. + + Creates a CustomMetric. + + Returns: + Callable[[~.CreateCustomMetricRequest], + Awaitable[~.CustomMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['create_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateCustomMetric', + request_serializer=analytics_admin.CreateCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['create_custom_metric'] + + @property + def update_custom_metric(self) -> Callable[ + [analytics_admin.UpdateCustomMetricRequest], + Awaitable[resources.CustomMetric]]: + r"""Return a callable for the update custom metric method over gRPC. + + Updates a CustomMetric on a property. + + Returns: + Callable[[~.UpdateCustomMetricRequest], + Awaitable[~.CustomMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['update_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateCustomMetric', + request_serializer=analytics_admin.UpdateCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['update_custom_metric'] + + @property + def list_custom_metrics(self) -> Callable[ + [analytics_admin.ListCustomMetricsRequest], + Awaitable[analytics_admin.ListCustomMetricsResponse]]: + r"""Return a callable for the list custom metrics method over gRPC. + + Lists CustomMetrics on a property. + + Returns: + Callable[[~.ListCustomMetricsRequest], + Awaitable[~.ListCustomMetricsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metrics' not in self._stubs: + self._stubs['list_custom_metrics'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListCustomMetrics', + request_serializer=analytics_admin.ListCustomMetricsRequest.serialize, + response_deserializer=analytics_admin.ListCustomMetricsResponse.deserialize, + ) + return self._stubs['list_custom_metrics'] + + @property + def archive_custom_metric(self) -> Callable[ + [analytics_admin.ArchiveCustomMetricRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the archive custom metric method over gRPC. + + Archives a CustomMetric on a property. + + Returns: + Callable[[~.ArchiveCustomMetricRequest], + 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 'archive_custom_metric' not in self._stubs: + self._stubs['archive_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ArchiveCustomMetric', + request_serializer=analytics_admin.ArchiveCustomMetricRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['archive_custom_metric'] + + @property + def get_custom_metric(self) -> Callable[ + [analytics_admin.GetCustomMetricRequest], + Awaitable[resources.CustomMetric]]: + r"""Return a callable for the get custom metric method over gRPC. + + Lookup for a single CustomMetric. + + Returns: + Callable[[~.GetCustomMetricRequest], + Awaitable[~.CustomMetric]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_custom_metric' not in self._stubs: + self._stubs['get_custom_metric'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetCustomMetric', + request_serializer=analytics_admin.GetCustomMetricRequest.serialize, + response_deserializer=resources.CustomMetric.deserialize, + ) + return self._stubs['get_custom_metric'] + + @property + def get_data_retention_settings(self) -> Callable[ + [analytics_admin.GetDataRetentionSettingsRequest], + Awaitable[resources.DataRetentionSettings]]: + r"""Return a callable for the get data retention settings method over gRPC. + + Returns the singleton data retention settings for + this property. + + Returns: + Callable[[~.GetDataRetentionSettingsRequest], + Awaitable[~.DataRetentionSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_retention_settings' not in self._stubs: + self._stubs['get_data_retention_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetDataRetentionSettings', + request_serializer=analytics_admin.GetDataRetentionSettingsRequest.serialize, + response_deserializer=resources.DataRetentionSettings.deserialize, + ) + return self._stubs['get_data_retention_settings'] + + @property + def update_data_retention_settings(self) -> Callable[ + [analytics_admin.UpdateDataRetentionSettingsRequest], + Awaitable[resources.DataRetentionSettings]]: + r"""Return a callable for the update data retention settings method over gRPC. + + Updates the singleton data retention settings for + this property. + + Returns: + Callable[[~.UpdateDataRetentionSettingsRequest], + Awaitable[~.DataRetentionSettings]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_retention_settings' not in self._stubs: + self._stubs['update_data_retention_settings'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateDataRetentionSettings', + request_serializer=analytics_admin.UpdateDataRetentionSettingsRequest.serialize, + response_deserializer=resources.DataRetentionSettings.deserialize, + ) + return self._stubs['update_data_retention_settings'] + + @property + def create_data_stream(self) -> Callable[ + [analytics_admin.CreateDataStreamRequest], + Awaitable[resources.DataStream]]: + r"""Return a callable for the create data stream method over gRPC. + + Creates a DataStream. + + Returns: + Callable[[~.CreateDataStreamRequest], + Awaitable[~.DataStream]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_data_stream' not in self._stubs: + self._stubs['create_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/CreateDataStream', + request_serializer=analytics_admin.CreateDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['create_data_stream'] + + @property + def delete_data_stream(self) -> Callable[ + [analytics_admin.DeleteDataStreamRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete data stream method over gRPC. + + Deletes a DataStream on a property. + + Returns: + Callable[[~.DeleteDataStreamRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_data_stream' not in self._stubs: + self._stubs['delete_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/DeleteDataStream', + request_serializer=analytics_admin.DeleteDataStreamRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_data_stream'] + + @property + def update_data_stream(self) -> Callable[ + [analytics_admin.UpdateDataStreamRequest], + Awaitable[resources.DataStream]]: + r"""Return a callable for the update data stream method over gRPC. + + Updates a DataStream on a property. + + Returns: + Callable[[~.UpdateDataStreamRequest], + Awaitable[~.DataStream]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_data_stream' not in self._stubs: + self._stubs['update_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/UpdateDataStream', + request_serializer=analytics_admin.UpdateDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['update_data_stream'] + + @property + def list_data_streams(self) -> Callable[ + [analytics_admin.ListDataStreamsRequest], + Awaitable[analytics_admin.ListDataStreamsResponse]]: + r"""Return a callable for the list data streams method over gRPC. + + Lists DataStreams on a property. + + Returns: + Callable[[~.ListDataStreamsRequest], + Awaitable[~.ListDataStreamsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'list_data_streams' not in self._stubs: + self._stubs['list_data_streams'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/ListDataStreams', + request_serializer=analytics_admin.ListDataStreamsRequest.serialize, + response_deserializer=analytics_admin.ListDataStreamsResponse.deserialize, + ) + return self._stubs['list_data_streams'] + + @property + def get_data_stream(self) -> Callable[ + [analytics_admin.GetDataStreamRequest], + Awaitable[resources.DataStream]]: + r"""Return a callable for the get data stream method over gRPC. + + Lookup for a single DataStream. + + Returns: + Callable[[~.GetDataStreamRequest], + Awaitable[~.DataStream]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'get_data_stream' not in self._stubs: + self._stubs['get_data_stream'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/GetDataStream', + request_serializer=analytics_admin.GetDataStreamRequest.serialize, + response_deserializer=resources.DataStream.deserialize, + ) + return self._stubs['get_data_stream'] + + @property + def run_access_report(self) -> Callable[ + [analytics_admin.RunAccessReportRequest], + Awaitable[analytics_admin.RunAccessReportResponse]]: + r"""Return a callable for the run access report method over gRPC. + + Returns a customized report of data access records. The report + provides records of each time a user reads Google Analytics + reporting data. Access records are retained for up to 2 years. + + Data Access Reports can be requested for a property. Reports may + be requested for any property, but dimensions that aren't + related to quota can only be requested on Google Analytics 360 + properties. This method is only available to Administrators. + + These data access records include GA4 UI Reporting, GA4 UI + Explorations, GA4 Data API, and other products like Firebase & + Admob that can retrieve data from Google Analytics through a + linkage. These records don't include property configuration + changes like adding a stream or changing a property's time zone. + For configuration change history, see + `searchChangeHistoryEvents `__. + + Returns: + Callable[[~.RunAccessReportRequest], + Awaitable[~.RunAccessReportResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'run_access_report' not in self._stubs: + self._stubs['run_access_report'] = self.grpc_channel.unary_unary( + '/google.analytics.admin.v1beta.AnalyticsAdminService/RunAccessReport', + request_serializer=analytics_admin.RunAccessReportRequest.serialize, + response_deserializer=analytics_admin.RunAccessReportResponse.deserialize, + ) + return self._stubs['run_access_report'] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.get_account: gapic_v1.method_async.wrap_method( + self.get_account, + default_timeout=None, + client_info=client_info, + ), + self.list_accounts: gapic_v1.method_async.wrap_method( + self.list_accounts, + default_timeout=None, + client_info=client_info, + ), + self.delete_account: gapic_v1.method_async.wrap_method( + self.delete_account, + default_timeout=None, + client_info=client_info, + ), + self.update_account: gapic_v1.method_async.wrap_method( + self.update_account, + default_timeout=None, + client_info=client_info, + ), + self.provision_account_ticket: gapic_v1.method_async.wrap_method( + self.provision_account_ticket, + default_timeout=None, + client_info=client_info, + ), + self.list_account_summaries: gapic_v1.method_async.wrap_method( + self.list_account_summaries, + default_timeout=None, + client_info=client_info, + ), + self.get_property: gapic_v1.method_async.wrap_method( + self.get_property, + default_timeout=None, + client_info=client_info, + ), + self.list_properties: gapic_v1.method_async.wrap_method( + self.list_properties, + default_timeout=None, + client_info=client_info, + ), + self.create_property: gapic_v1.method_async.wrap_method( + self.create_property, + default_timeout=None, + client_info=client_info, + ), + self.delete_property: gapic_v1.method_async.wrap_method( + self.delete_property, + default_timeout=None, + client_info=client_info, + ), + self.update_property: gapic_v1.method_async.wrap_method( + self.update_property, + default_timeout=None, + client_info=client_info, + ), + self.create_firebase_link: gapic_v1.method_async.wrap_method( + self.create_firebase_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_firebase_link: gapic_v1.method_async.wrap_method( + self.delete_firebase_link, + default_timeout=None, + client_info=client_info, + ), + self.list_firebase_links: gapic_v1.method_async.wrap_method( + self.list_firebase_links, + default_timeout=None, + client_info=client_info, + ), + self.create_google_ads_link: gapic_v1.method_async.wrap_method( + self.create_google_ads_link, + default_timeout=None, + client_info=client_info, + ), + self.update_google_ads_link: gapic_v1.method_async.wrap_method( + self.update_google_ads_link, + default_timeout=None, + client_info=client_info, + ), + self.delete_google_ads_link: gapic_v1.method_async.wrap_method( + self.delete_google_ads_link, + default_timeout=None, + client_info=client_info, + ), + self.list_google_ads_links: gapic_v1.method_async.wrap_method( + self.list_google_ads_links, + default_timeout=None, + client_info=client_info, + ), + self.get_data_sharing_settings: gapic_v1.method_async.wrap_method( + self.get_data_sharing_settings, + default_timeout=None, + client_info=client_info, + ), + self.get_measurement_protocol_secret: gapic_v1.method_async.wrap_method( + self.get_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.list_measurement_protocol_secrets: gapic_v1.method_async.wrap_method( + self.list_measurement_protocol_secrets, + default_timeout=None, + client_info=client_info, + ), + self.create_measurement_protocol_secret: gapic_v1.method_async.wrap_method( + self.create_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.delete_measurement_protocol_secret: gapic_v1.method_async.wrap_method( + self.delete_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.update_measurement_protocol_secret: gapic_v1.method_async.wrap_method( + self.update_measurement_protocol_secret, + default_timeout=None, + client_info=client_info, + ), + self.acknowledge_user_data_collection: gapic_v1.method_async.wrap_method( + self.acknowledge_user_data_collection, + default_timeout=None, + client_info=client_info, + ), + self.search_change_history_events: gapic_v1.method_async.wrap_method( + self.search_change_history_events, + default_timeout=None, + client_info=client_info, + ), + self.create_conversion_event: gapic_v1.method_async.wrap_method( + self.create_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.update_conversion_event: gapic_v1.method_async.wrap_method( + self.update_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.get_conversion_event: gapic_v1.method_async.wrap_method( + self.get_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversion_event: gapic_v1.method_async.wrap_method( + self.delete_conversion_event, + default_timeout=None, + client_info=client_info, + ), + self.list_conversion_events: gapic_v1.method_async.wrap_method( + self.list_conversion_events, + default_timeout=None, + client_info=client_info, + ), + self.create_key_event: gapic_v1.method_async.wrap_method( + self.create_key_event, + default_timeout=None, + client_info=client_info, + ), + self.update_key_event: gapic_v1.method_async.wrap_method( + self.update_key_event, + default_timeout=None, + client_info=client_info, + ), + self.get_key_event: gapic_v1.method_async.wrap_method( + self.get_key_event, + default_timeout=None, + client_info=client_info, + ), + self.delete_key_event: gapic_v1.method_async.wrap_method( + self.delete_key_event, + default_timeout=None, + client_info=client_info, + ), + self.list_key_events: gapic_v1.method_async.wrap_method( + self.list_key_events, + default_timeout=None, + client_info=client_info, + ), + self.create_custom_dimension: gapic_v1.method_async.wrap_method( + self.create_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.update_custom_dimension: gapic_v1.method_async.wrap_method( + self.update_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.list_custom_dimensions: gapic_v1.method_async.wrap_method( + self.list_custom_dimensions, + default_timeout=None, + client_info=client_info, + ), + self.archive_custom_dimension: gapic_v1.method_async.wrap_method( + self.archive_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.get_custom_dimension: gapic_v1.method_async.wrap_method( + self.get_custom_dimension, + default_timeout=None, + client_info=client_info, + ), + self.create_custom_metric: gapic_v1.method_async.wrap_method( + self.create_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.update_custom_metric: gapic_v1.method_async.wrap_method( + self.update_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.list_custom_metrics: gapic_v1.method_async.wrap_method( + self.list_custom_metrics, + default_timeout=None, + client_info=client_info, + ), + self.archive_custom_metric: gapic_v1.method_async.wrap_method( + self.archive_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.get_custom_metric: gapic_v1.method_async.wrap_method( + self.get_custom_metric, + default_timeout=None, + client_info=client_info, + ), + self.get_data_retention_settings: gapic_v1.method_async.wrap_method( + self.get_data_retention_settings, + default_timeout=None, + client_info=client_info, + ), + self.update_data_retention_settings: gapic_v1.method_async.wrap_method( + self.update_data_retention_settings, + default_timeout=None, + client_info=client_info, + ), + self.create_data_stream: gapic_v1.method_async.wrap_method( + self.create_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.delete_data_stream: gapic_v1.method_async.wrap_method( + self.delete_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.update_data_stream: gapic_v1.method_async.wrap_method( + self.update_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.list_data_streams: gapic_v1.method_async.wrap_method( + self.list_data_streams, + default_timeout=None, + client_info=client_info, + ), + self.get_data_stream: gapic_v1.method_async.wrap_method( + self.get_data_stream, + default_timeout=None, + client_info=client_info, + ), + self.run_access_report: gapic_v1.method_async.wrap_method( + self.run_access_report, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AnalyticsAdminServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/rest.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/rest.py new file mode 100644 index 000000000000..ce3b34c5267b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/services/analytics_admin_service/transports/rest.py @@ -0,0 +1,6158 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1beta.types import analytics_admin +from google.analytics.admin_v1beta.types import resources +from google.protobuf import empty_pb2 # type: ignore + +from .base import AnalyticsAdminServiceTransport, 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 AnalyticsAdminServiceRestInterceptor: + """Interceptor for AnalyticsAdminService. + + 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 AnalyticsAdminServiceRestTransport. + + .. code-block:: python + class MyCustomAnalyticsAdminServiceInterceptor(AnalyticsAdminServiceRestInterceptor): + def pre_acknowledge_user_data_collection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_acknowledge_user_data_collection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_archive_custom_dimension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_archive_custom_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_create_conversion_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_conversion_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_custom_dimension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_dimension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_custom_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_custom_metric(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_data_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_data_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_firebase_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_firebase_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_google_ads_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_google_ads_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_key_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_measurement_protocol_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_measurement_protocol_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_property(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_conversion_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_data_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_firebase_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_google_ads_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_measurement_protocol_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_property(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_conversion_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_conversion_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_custom_dimension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_dimension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_custom_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_custom_metric(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_retention_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_retention_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_sharing_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_sharing_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_data_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_data_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_key_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_measurement_protocol_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_measurement_protocol_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_property(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_accounts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_accounts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_account_summaries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_account_summaries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_conversion_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_conversion_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_dimensions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_dimensions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_custom_metrics(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_custom_metrics(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_data_streams(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_data_streams(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_firebase_links(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_firebase_links(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_google_ads_links(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_google_ads_links(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_key_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_key_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_measurement_protocol_secrets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_measurement_protocol_secrets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_properties(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_properties(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_provision_account_ticket(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_provision_account_ticket(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_run_access_report(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_access_report(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_change_history_events(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_change_history_events(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_conversion_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_conversion_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_dimension(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_dimension(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_custom_metric(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_custom_metric(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_retention_settings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_retention_settings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_data_stream(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_data_stream(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_google_ads_link(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_google_ads_link(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_key_event(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_key_event(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_measurement_protocol_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_measurement_protocol_secret(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_property(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_property(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AnalyticsAdminServiceRestTransport(interceptor=MyCustomAnalyticsAdminServiceInterceptor()) + client = AnalyticsAdminServiceClient(transport=transport) + + + """ + def pre_acknowledge_user_data_collection(self, request: analytics_admin.AcknowledgeUserDataCollectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.AcknowledgeUserDataCollectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for acknowledge_user_data_collection + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_acknowledge_user_data_collection(self, response: analytics_admin.AcknowledgeUserDataCollectionResponse) -> analytics_admin.AcknowledgeUserDataCollectionResponse: + """Post-rpc interceptor for acknowledge_user_data_collection + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_archive_custom_dimension(self, request: analytics_admin.ArchiveCustomDimensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ArchiveCustomDimensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for archive_custom_dimension + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_archive_custom_metric(self, request: analytics_admin.ArchiveCustomMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ArchiveCustomMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for archive_custom_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_create_conversion_event(self, request: analytics_admin.CreateConversionEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateConversionEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_conversion_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_conversion_event(self, response: resources.ConversionEvent) -> resources.ConversionEvent: + """Post-rpc interceptor for create_conversion_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_custom_dimension(self, request: analytics_admin.CreateCustomDimensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateCustomDimensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_custom_dimension + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_custom_dimension(self, response: resources.CustomDimension) -> resources.CustomDimension: + """Post-rpc interceptor for create_custom_dimension + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_custom_metric(self, request: analytics_admin.CreateCustomMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateCustomMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_custom_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_custom_metric(self, response: resources.CustomMetric) -> resources.CustomMetric: + """Post-rpc interceptor for create_custom_metric + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_data_stream(self, request: analytics_admin.CreateDataStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateDataStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_data_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_data_stream(self, response: resources.DataStream) -> resources.DataStream: + """Post-rpc interceptor for create_data_stream + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_firebase_link(self, request: analytics_admin.CreateFirebaseLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateFirebaseLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_firebase_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_firebase_link(self, response: resources.FirebaseLink) -> resources.FirebaseLink: + """Post-rpc interceptor for create_firebase_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_google_ads_link(self, request: analytics_admin.CreateGoogleAdsLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateGoogleAdsLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_google_ads_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_google_ads_link(self, response: resources.GoogleAdsLink) -> resources.GoogleAdsLink: + """Post-rpc interceptor for create_google_ads_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_key_event(self, request: analytics_admin.CreateKeyEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_key_event(self, response: resources.KeyEvent) -> resources.KeyEvent: + """Post-rpc interceptor for create_key_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_measurement_protocol_secret(self, request: analytics_admin.CreateMeasurementProtocolSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreateMeasurementProtocolSecretRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_measurement_protocol_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_measurement_protocol_secret(self, response: resources.MeasurementProtocolSecret) -> resources.MeasurementProtocolSecret: + """Post-rpc interceptor for create_measurement_protocol_secret + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_create_property(self, request: analytics_admin.CreatePropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.CreatePropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_create_property(self, response: resources.Property) -> resources.Property: + """Post-rpc interceptor for create_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_delete_account(self, request: analytics_admin.DeleteAccountRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_conversion_event(self, request: analytics_admin.DeleteConversionEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteConversionEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_conversion_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_data_stream(self, request: analytics_admin.DeleteDataStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteDataStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_data_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_firebase_link(self, request: analytics_admin.DeleteFirebaseLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteFirebaseLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_firebase_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_google_ads_link(self, request: analytics_admin.DeleteGoogleAdsLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteGoogleAdsLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_google_ads_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_key_event(self, request: analytics_admin.DeleteKeyEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_measurement_protocol_secret(self, request: analytics_admin.DeleteMeasurementProtocolSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeleteMeasurementProtocolSecretRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_measurement_protocol_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def pre_delete_property(self, request: analytics_admin.DeletePropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.DeletePropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_delete_property(self, response: resources.Property) -> resources.Property: + """Post-rpc interceptor for delete_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_account(self, request: analytics_admin.GetAccountRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_account(self, response: resources.Account) -> resources.Account: + """Post-rpc interceptor for get_account + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_conversion_event(self, request: analytics_admin.GetConversionEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetConversionEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_conversion_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_conversion_event(self, response: resources.ConversionEvent) -> resources.ConversionEvent: + """Post-rpc interceptor for get_conversion_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_custom_dimension(self, request: analytics_admin.GetCustomDimensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetCustomDimensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_custom_dimension + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_custom_dimension(self, response: resources.CustomDimension) -> resources.CustomDimension: + """Post-rpc interceptor for get_custom_dimension + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_custom_metric(self, request: analytics_admin.GetCustomMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetCustomMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_custom_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_custom_metric(self, response: resources.CustomMetric) -> resources.CustomMetric: + """Post-rpc interceptor for get_custom_metric + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_data_retention_settings(self, request: analytics_admin.GetDataRetentionSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetDataRetentionSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_retention_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_data_retention_settings(self, response: resources.DataRetentionSettings) -> resources.DataRetentionSettings: + """Post-rpc interceptor for get_data_retention_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_data_sharing_settings(self, request: analytics_admin.GetDataSharingSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetDataSharingSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_sharing_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_data_sharing_settings(self, response: resources.DataSharingSettings) -> resources.DataSharingSettings: + """Post-rpc interceptor for get_data_sharing_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_data_stream(self, request: analytics_admin.GetDataStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetDataStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_data_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_data_stream(self, response: resources.DataStream) -> resources.DataStream: + """Post-rpc interceptor for get_data_stream + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_key_event(self, request: analytics_admin.GetKeyEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_key_event(self, response: resources.KeyEvent) -> resources.KeyEvent: + """Post-rpc interceptor for get_key_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_measurement_protocol_secret(self, request: analytics_admin.GetMeasurementProtocolSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetMeasurementProtocolSecretRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_measurement_protocol_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_measurement_protocol_secret(self, response: resources.MeasurementProtocolSecret) -> resources.MeasurementProtocolSecret: + """Post-rpc interceptor for get_measurement_protocol_secret + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_get_property(self, request: analytics_admin.GetPropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.GetPropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_get_property(self, response: resources.Property) -> resources.Property: + """Post-rpc interceptor for get_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_accounts(self, request: analytics_admin.ListAccountsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListAccountsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_accounts + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_accounts(self, response: analytics_admin.ListAccountsResponse) -> analytics_admin.ListAccountsResponse: + """Post-rpc interceptor for list_accounts + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_account_summaries(self, request: analytics_admin.ListAccountSummariesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListAccountSummariesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_account_summaries + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_account_summaries(self, response: analytics_admin.ListAccountSummariesResponse) -> analytics_admin.ListAccountSummariesResponse: + """Post-rpc interceptor for list_account_summaries + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_conversion_events(self, request: analytics_admin.ListConversionEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListConversionEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_conversion_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_conversion_events(self, response: analytics_admin.ListConversionEventsResponse) -> analytics_admin.ListConversionEventsResponse: + """Post-rpc interceptor for list_conversion_events + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_custom_dimensions(self, request: analytics_admin.ListCustomDimensionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListCustomDimensionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_custom_dimensions + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_custom_dimensions(self, response: analytics_admin.ListCustomDimensionsResponse) -> analytics_admin.ListCustomDimensionsResponse: + """Post-rpc interceptor for list_custom_dimensions + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_custom_metrics(self, request: analytics_admin.ListCustomMetricsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListCustomMetricsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_custom_metrics + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_custom_metrics(self, response: analytics_admin.ListCustomMetricsResponse) -> analytics_admin.ListCustomMetricsResponse: + """Post-rpc interceptor for list_custom_metrics + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_data_streams(self, request: analytics_admin.ListDataStreamsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListDataStreamsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_data_streams + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_data_streams(self, response: analytics_admin.ListDataStreamsResponse) -> analytics_admin.ListDataStreamsResponse: + """Post-rpc interceptor for list_data_streams + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_firebase_links(self, request: analytics_admin.ListFirebaseLinksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListFirebaseLinksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_firebase_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_firebase_links(self, response: analytics_admin.ListFirebaseLinksResponse) -> analytics_admin.ListFirebaseLinksResponse: + """Post-rpc interceptor for list_firebase_links + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_google_ads_links(self, request: analytics_admin.ListGoogleAdsLinksRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListGoogleAdsLinksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_google_ads_links + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_google_ads_links(self, response: analytics_admin.ListGoogleAdsLinksResponse) -> analytics_admin.ListGoogleAdsLinksResponse: + """Post-rpc interceptor for list_google_ads_links + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_key_events(self, request: analytics_admin.ListKeyEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListKeyEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_key_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_key_events(self, response: analytics_admin.ListKeyEventsResponse) -> analytics_admin.ListKeyEventsResponse: + """Post-rpc interceptor for list_key_events + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_measurement_protocol_secrets(self, request: analytics_admin.ListMeasurementProtocolSecretsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListMeasurementProtocolSecretsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_measurement_protocol_secrets + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_measurement_protocol_secrets(self, response: analytics_admin.ListMeasurementProtocolSecretsResponse) -> analytics_admin.ListMeasurementProtocolSecretsResponse: + """Post-rpc interceptor for list_measurement_protocol_secrets + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_list_properties(self, request: analytics_admin.ListPropertiesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ListPropertiesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_properties + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_list_properties(self, response: analytics_admin.ListPropertiesResponse) -> analytics_admin.ListPropertiesResponse: + """Post-rpc interceptor for list_properties + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_provision_account_ticket(self, request: analytics_admin.ProvisionAccountTicketRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.ProvisionAccountTicketRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for provision_account_ticket + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_provision_account_ticket(self, response: analytics_admin.ProvisionAccountTicketResponse) -> analytics_admin.ProvisionAccountTicketResponse: + """Post-rpc interceptor for provision_account_ticket + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_run_access_report(self, request: analytics_admin.RunAccessReportRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.RunAccessReportRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for run_access_report + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_run_access_report(self, response: analytics_admin.RunAccessReportResponse) -> analytics_admin.RunAccessReportResponse: + """Post-rpc interceptor for run_access_report + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_search_change_history_events(self, request: analytics_admin.SearchChangeHistoryEventsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.SearchChangeHistoryEventsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_change_history_events + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_search_change_history_events(self, response: analytics_admin.SearchChangeHistoryEventsResponse) -> analytics_admin.SearchChangeHistoryEventsResponse: + """Post-rpc interceptor for search_change_history_events + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_account(self, request: analytics_admin.UpdateAccountRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_account(self, response: resources.Account) -> resources.Account: + """Post-rpc interceptor for update_account + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_conversion_event(self, request: analytics_admin.UpdateConversionEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateConversionEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_conversion_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_conversion_event(self, response: resources.ConversionEvent) -> resources.ConversionEvent: + """Post-rpc interceptor for update_conversion_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_custom_dimension(self, request: analytics_admin.UpdateCustomDimensionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateCustomDimensionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_custom_dimension + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_custom_dimension(self, response: resources.CustomDimension) -> resources.CustomDimension: + """Post-rpc interceptor for update_custom_dimension + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_custom_metric(self, request: analytics_admin.UpdateCustomMetricRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateCustomMetricRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_custom_metric + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_custom_metric(self, response: resources.CustomMetric) -> resources.CustomMetric: + """Post-rpc interceptor for update_custom_metric + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_data_retention_settings(self, request: analytics_admin.UpdateDataRetentionSettingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateDataRetentionSettingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_data_retention_settings + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_data_retention_settings(self, response: resources.DataRetentionSettings) -> resources.DataRetentionSettings: + """Post-rpc interceptor for update_data_retention_settings + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_data_stream(self, request: analytics_admin.UpdateDataStreamRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateDataStreamRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_data_stream + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_data_stream(self, response: resources.DataStream) -> resources.DataStream: + """Post-rpc interceptor for update_data_stream + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_google_ads_link(self, request: analytics_admin.UpdateGoogleAdsLinkRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateGoogleAdsLinkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_google_ads_link + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_google_ads_link(self, response: resources.GoogleAdsLink) -> resources.GoogleAdsLink: + """Post-rpc interceptor for update_google_ads_link + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_key_event(self, request: analytics_admin.UpdateKeyEventRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateKeyEventRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_key_event + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_key_event(self, response: resources.KeyEvent) -> resources.KeyEvent: + """Post-rpc interceptor for update_key_event + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_measurement_protocol_secret(self, request: analytics_admin.UpdateMeasurementProtocolSecretRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdateMeasurementProtocolSecretRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_measurement_protocol_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_measurement_protocol_secret(self, response: resources.MeasurementProtocolSecret) -> resources.MeasurementProtocolSecret: + """Post-rpc interceptor for update_measurement_protocol_secret + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + def pre_update_property(self, request: analytics_admin.UpdatePropertyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[analytics_admin.UpdatePropertyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_property + + Override in a subclass to manipulate the request or metadata + before they are sent to the AnalyticsAdminService server. + """ + return request, metadata + + def post_update_property(self, response: resources.Property) -> resources.Property: + """Post-rpc interceptor for update_property + + Override in a subclass to manipulate the response + after it is returned by the AnalyticsAdminService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AnalyticsAdminServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AnalyticsAdminServiceRestInterceptor + + +class AnalyticsAdminServiceRestTransport(AnalyticsAdminServiceTransport): + """REST backend transport for AnalyticsAdminService. + + Service Interface for the Analytics Admin API (GA4). + + 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 = 'analyticsadmin.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[AnalyticsAdminServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'analyticsadmin.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 AnalyticsAdminServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AcknowledgeUserDataCollection(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("AcknowledgeUserDataCollection") + + __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: analytics_admin.AcknowledgeUserDataCollectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.AcknowledgeUserDataCollectionResponse: + r"""Call the acknowledge user data + collection method over HTTP. + + Args: + request (~.analytics_admin.AcknowledgeUserDataCollectionRequest): + The request object. Request message for + AcknowledgeUserDataCollection RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.AcknowledgeUserDataCollectionResponse: + Response message for + AcknowledgeUserDataCollection RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{property=properties/*}:acknowledgeUserDataCollection', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_acknowledge_user_data_collection(request, metadata) + pb_request = analytics_admin.AcknowledgeUserDataCollectionRequest.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 = analytics_admin.AcknowledgeUserDataCollectionResponse() + pb_resp = analytics_admin.AcknowledgeUserDataCollectionResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_acknowledge_user_data_collection(resp) + return resp + + class _ArchiveCustomDimension(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ArchiveCustomDimension") + + __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: analytics_admin.ArchiveCustomDimensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the archive custom dimension method over HTTP. + + Args: + request (~.analytics_admin.ArchiveCustomDimensionRequest): + The request object. Request message for + ArchiveCustomDimension RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{name=properties/*/customDimensions/*}:archive', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_archive_custom_dimension(request, metadata) + pb_request = analytics_admin.ArchiveCustomDimensionRequest.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) + + class _ArchiveCustomMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ArchiveCustomMetric") + + __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: analytics_admin.ArchiveCustomMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the archive custom metric method over HTTP. + + Args: + request (~.analytics_admin.ArchiveCustomMetricRequest): + The request object. Request message for + ArchiveCustomMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{name=properties/*/customMetrics/*}:archive', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_archive_custom_metric(request, metadata) + pb_request = analytics_admin.ArchiveCustomMetricRequest.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) + + class _CreateConversionEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateConversionEvent") + + __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: analytics_admin.CreateConversionEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ConversionEvent: + r"""Call the create conversion event method over HTTP. + + Args: + request (~.analytics_admin.CreateConversionEventRequest): + The request object. Request message for + CreateConversionEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=properties/*}/conversionEvents', + 'body': 'conversion_event', + }, + ] + request, metadata = self._interceptor.pre_create_conversion_event(request, metadata) + pb_request = analytics_admin.CreateConversionEventRequest.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 = resources.ConversionEvent() + pb_resp = resources.ConversionEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_conversion_event(resp) + return resp + + class _CreateCustomDimension(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateCustomDimension") + + __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: analytics_admin.CreateCustomDimensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomDimension: + r"""Call the create custom dimension method over HTTP. + + Args: + request (~.analytics_admin.CreateCustomDimensionRequest): + The request object. Request message for + CreateCustomDimension RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomDimension: + A definition for a CustomDimension. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=properties/*}/customDimensions', + 'body': 'custom_dimension', + }, + ] + request, metadata = self._interceptor.pre_create_custom_dimension(request, metadata) + pb_request = analytics_admin.CreateCustomDimensionRequest.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 = resources.CustomDimension() + pb_resp = resources.CustomDimension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_custom_dimension(resp) + return resp + + class _CreateCustomMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateCustomMetric") + + __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: analytics_admin.CreateCustomMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomMetric: + r"""Call the create custom metric method over HTTP. + + Args: + request (~.analytics_admin.CreateCustomMetricRequest): + The request object. Request message for + CreateCustomMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomMetric: + A definition for a custom metric. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=properties/*}/customMetrics', + 'body': 'custom_metric', + }, + ] + request, metadata = self._interceptor.pre_create_custom_metric(request, metadata) + pb_request = analytics_admin.CreateCustomMetricRequest.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 = resources.CustomMetric() + pb_resp = resources.CustomMetric.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_custom_metric(resp) + return resp + + class _CreateDataStream(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateDataStream") + + __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: analytics_admin.CreateDataStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataStream: + r"""Call the create data stream method over HTTP. + + Args: + request (~.analytics_admin.CreateDataStreamRequest): + The request object. Request message for CreateDataStream + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataStream: + A resource message representing a + data stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=properties/*}/dataStreams', + 'body': 'data_stream', + }, + ] + request, metadata = self._interceptor.pre_create_data_stream(request, metadata) + pb_request = analytics_admin.CreateDataStreamRequest.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 = resources.DataStream() + pb_resp = resources.DataStream.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_data_stream(resp) + return resp + + class _CreateFirebaseLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateFirebaseLink") + + __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: analytics_admin.CreateFirebaseLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.FirebaseLink: + r"""Call the create firebase link method over HTTP. + + Args: + request (~.analytics_admin.CreateFirebaseLinkRequest): + The request object. Request message for + CreateFirebaseLink RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.FirebaseLink: + A link between a GA4 property and a + Firebase project. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=properties/*}/firebaseLinks', + 'body': 'firebase_link', + }, + ] + request, metadata = self._interceptor.pre_create_firebase_link(request, metadata) + pb_request = analytics_admin.CreateFirebaseLinkRequest.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 = resources.FirebaseLink() + pb_resp = resources.FirebaseLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_firebase_link(resp) + return resp + + class _CreateGoogleAdsLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateGoogleAdsLink") + + __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: analytics_admin.CreateGoogleAdsLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.GoogleAdsLink: + r"""Call the create google ads link method over HTTP. + + Args: + request (~.analytics_admin.CreateGoogleAdsLinkRequest): + The request object. Request message for + CreateGoogleAdsLink RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=properties/*}/googleAdsLinks', + 'body': 'google_ads_link', + }, + ] + request, metadata = self._interceptor.pre_create_google_ads_link(request, metadata) + pb_request = analytics_admin.CreateGoogleAdsLinkRequest.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 = resources.GoogleAdsLink() + pb_resp = resources.GoogleAdsLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_google_ads_link(resp) + return resp + + class _CreateKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateKeyEvent") + + __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: analytics_admin.CreateKeyEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.KeyEvent: + r"""Call the create key event method over HTTP. + + Args: + request (~.analytics_admin.CreateKeyEventRequest): + The request object. Request message for CreateKeyEvent + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.KeyEvent: + A key event in a Google Analytics + property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=properties/*}/keyEvents', + 'body': 'key_event', + }, + ] + request, metadata = self._interceptor.pre_create_key_event(request, metadata) + pb_request = analytics_admin.CreateKeyEventRequest.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 = resources.KeyEvent() + pb_resp = resources.KeyEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_key_event(resp) + return resp + + class _CreateMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateMeasurementProtocolSecret") + + __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: analytics_admin.CreateMeasurementProtocolSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.MeasurementProtocolSecret: + r"""Call the create measurement + protocol secret method over HTTP. + + Args: + request (~.analytics_admin.CreateMeasurementProtocolSecretRequest): + The request object. Request message for + CreateMeasurementProtocolSecret RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets', + 'body': 'measurement_protocol_secret', + }, + ] + request, metadata = self._interceptor.pre_create_measurement_protocol_secret(request, metadata) + pb_request = analytics_admin.CreateMeasurementProtocolSecretRequest.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 = resources.MeasurementProtocolSecret() + pb_resp = resources.MeasurementProtocolSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_measurement_protocol_secret(resp) + return resp + + class _CreateProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("CreateProperty") + + __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: analytics_admin.CreatePropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Property: + r"""Call the create property method over HTTP. + + Args: + request (~.analytics_admin.CreatePropertyRequest): + The request object. Request message for CreateProperty + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/properties', + 'body': 'property', + }, + ] + request, metadata = self._interceptor.pre_create_property(request, metadata) + pb_request = analytics_admin.CreatePropertyRequest.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 = resources.Property() + pb_resp = resources.Property.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_property(resp) + return resp + + class _DeleteAccount(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteAccount") + + __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: analytics_admin.DeleteAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete account method over HTTP. + + Args: + request (~.analytics_admin.DeleteAccountRequest): + The request object. Request message for DeleteAccount + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1beta/{name=accounts/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_account(request, metadata) + pb_request = analytics_admin.DeleteAccountRequest.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 _DeleteConversionEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteConversionEvent") + + __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: analytics_admin.DeleteConversionEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete conversion event method over HTTP. + + Args: + request (~.analytics_admin.DeleteConversionEventRequest): + The request object. Request message for + DeleteConversionEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1beta/{name=properties/*/conversionEvents/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_conversion_event(request, metadata) + pb_request = analytics_admin.DeleteConversionEventRequest.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 _DeleteDataStream(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteDataStream") + + __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: analytics_admin.DeleteDataStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete data stream method over HTTP. + + Args: + request (~.analytics_admin.DeleteDataStreamRequest): + The request object. Request message for DeleteDataStream + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1beta/{name=properties/*/dataStreams/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_data_stream(request, metadata) + pb_request = analytics_admin.DeleteDataStreamRequest.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 _DeleteFirebaseLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteFirebaseLink") + + __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: analytics_admin.DeleteFirebaseLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete firebase link method over HTTP. + + Args: + request (~.analytics_admin.DeleteFirebaseLinkRequest): + The request object. Request message for + DeleteFirebaseLink RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1beta/{name=properties/*/firebaseLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_firebase_link(request, metadata) + pb_request = analytics_admin.DeleteFirebaseLinkRequest.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 _DeleteGoogleAdsLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteGoogleAdsLink") + + __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: analytics_admin.DeleteGoogleAdsLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete google ads link method over HTTP. + + Args: + request (~.analytics_admin.DeleteGoogleAdsLinkRequest): + The request object. Request message for + DeleteGoogleAdsLink RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1beta/{name=properties/*/googleAdsLinks/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_google_ads_link(request, metadata) + pb_request = analytics_admin.DeleteGoogleAdsLinkRequest.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 _DeleteKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteKeyEvent") + + __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: analytics_admin.DeleteKeyEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete key event method over HTTP. + + Args: + request (~.analytics_admin.DeleteKeyEventRequest): + The request object. Request message for DeleteKeyEvent + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1beta/{name=properties/*/keyEvents/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_key_event(request, metadata) + pb_request = analytics_admin.DeleteKeyEventRequest.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 _DeleteMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteMeasurementProtocolSecret") + + __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: analytics_admin.DeleteMeasurementProtocolSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete measurement + protocol secret method over HTTP. + + Args: + request (~.analytics_admin.DeleteMeasurementProtocolSecretRequest): + The request object. Request message for + DeleteMeasurementProtocolSecret RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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': '/v1beta/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_measurement_protocol_secret(request, metadata) + pb_request = analytics_admin.DeleteMeasurementProtocolSecretRequest.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 _DeleteProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("DeleteProperty") + + __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: analytics_admin.DeletePropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Property: + r"""Call the delete property method over HTTP. + + Args: + request (~.analytics_admin.DeletePropertyRequest): + The request object. Request message for DeleteProperty + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1beta/{name=properties/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_property(request, metadata) + pb_request = analytics_admin.DeletePropertyRequest.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 = resources.Property() + pb_resp = resources.Property.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_property(resp) + return resp + + class _GetAccount(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetAccount") + + __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: analytics_admin.GetAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Account: + r"""Call the get account method over HTTP. + + Args: + request (~.analytics_admin.GetAccountRequest): + The request object. Request message for GetAccount RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Account: + A resource message representing a + Google Analytics account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=accounts/*}', + }, + ] + request, metadata = self._interceptor.pre_get_account(request, metadata) + pb_request = analytics_admin.GetAccountRequest.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 = resources.Account() + pb_resp = resources.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_account(resp) + return resp + + class _GetConversionEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetConversionEvent") + + __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: analytics_admin.GetConversionEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ConversionEvent: + r"""Call the get conversion event method over HTTP. + + Args: + request (~.analytics_admin.GetConversionEventRequest): + The request object. Request message for + GetConversionEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=properties/*/conversionEvents/*}', + }, + ] + request, metadata = self._interceptor.pre_get_conversion_event(request, metadata) + pb_request = analytics_admin.GetConversionEventRequest.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 = resources.ConversionEvent() + pb_resp = resources.ConversionEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_conversion_event(resp) + return resp + + class _GetCustomDimension(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetCustomDimension") + + __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: analytics_admin.GetCustomDimensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomDimension: + r"""Call the get custom dimension method over HTTP. + + Args: + request (~.analytics_admin.GetCustomDimensionRequest): + The request object. Request message for + GetCustomDimension RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomDimension: + A definition for a CustomDimension. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=properties/*/customDimensions/*}', + }, + ] + request, metadata = self._interceptor.pre_get_custom_dimension(request, metadata) + pb_request = analytics_admin.GetCustomDimensionRequest.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 = resources.CustomDimension() + pb_resp = resources.CustomDimension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_custom_dimension(resp) + return resp + + class _GetCustomMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetCustomMetric") + + __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: analytics_admin.GetCustomMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomMetric: + r"""Call the get custom metric method over HTTP. + + Args: + request (~.analytics_admin.GetCustomMetricRequest): + The request object. Request message for GetCustomMetric + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomMetric: + A definition for a custom metric. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=properties/*/customMetrics/*}', + }, + ] + request, metadata = self._interceptor.pre_get_custom_metric(request, metadata) + pb_request = analytics_admin.GetCustomMetricRequest.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 = resources.CustomMetric() + pb_resp = resources.CustomMetric.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_custom_metric(resp) + return resp + + class _GetDataRetentionSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetDataRetentionSettings") + + __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: analytics_admin.GetDataRetentionSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataRetentionSettings: + r"""Call the get data retention + settings method over HTTP. + + Args: + request (~.analytics_admin.GetDataRetentionSettingsRequest): + The request object. Request message for + GetDataRetentionSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=properties/*/dataRetentionSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_data_retention_settings(request, metadata) + pb_request = analytics_admin.GetDataRetentionSettingsRequest.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 = resources.DataRetentionSettings() + pb_resp = resources.DataRetentionSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_retention_settings(resp) + return resp + + class _GetDataSharingSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetDataSharingSettings") + + __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: analytics_admin.GetDataSharingSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataSharingSettings: + r"""Call the get data sharing settings method over HTTP. + + Args: + request (~.analytics_admin.GetDataSharingSettingsRequest): + The request object. Request message for + GetDataSharingSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataSharingSettings: + A resource message representing data + sharing settings of a Google Analytics + account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=accounts/*/dataSharingSettings}', + }, + ] + request, metadata = self._interceptor.pre_get_data_sharing_settings(request, metadata) + pb_request = analytics_admin.GetDataSharingSettingsRequest.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 = resources.DataSharingSettings() + pb_resp = resources.DataSharingSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_sharing_settings(resp) + return resp + + class _GetDataStream(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetDataStream") + + __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: analytics_admin.GetDataStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataStream: + r"""Call the get data stream method over HTTP. + + Args: + request (~.analytics_admin.GetDataStreamRequest): + The request object. Request message for GetDataStream + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataStream: + A resource message representing a + data stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=properties/*/dataStreams/*}', + }, + ] + request, metadata = self._interceptor.pre_get_data_stream(request, metadata) + pb_request = analytics_admin.GetDataStreamRequest.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 = resources.DataStream() + pb_resp = resources.DataStream.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_data_stream(resp) + return resp + + class _GetKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetKeyEvent") + + __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: analytics_admin.GetKeyEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.KeyEvent: + r"""Call the get key event method over HTTP. + + Args: + request (~.analytics_admin.GetKeyEventRequest): + The request object. Request message for GetKeyEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.KeyEvent: + A key event in a Google Analytics + property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=properties/*/keyEvents/*}', + }, + ] + request, metadata = self._interceptor.pre_get_key_event(request, metadata) + pb_request = analytics_admin.GetKeyEventRequest.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 = resources.KeyEvent() + pb_resp = resources.KeyEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_key_event(resp) + return resp + + class _GetMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetMeasurementProtocolSecret") + + __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: analytics_admin.GetMeasurementProtocolSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.MeasurementProtocolSecret: + r"""Call the get measurement protocol + secret method over HTTP. + + Args: + request (~.analytics_admin.GetMeasurementProtocolSecretRequest): + The request object. Request message for + GetMeasurementProtocolSecret RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}', + }, + ] + request, metadata = self._interceptor.pre_get_measurement_protocol_secret(request, metadata) + pb_request = analytics_admin.GetMeasurementProtocolSecretRequest.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 = resources.MeasurementProtocolSecret() + pb_resp = resources.MeasurementProtocolSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_measurement_protocol_secret(resp) + return resp + + class _GetProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("GetProperty") + + __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: analytics_admin.GetPropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Property: + r"""Call the get property method over HTTP. + + Args: + request (~.analytics_admin.GetPropertyRequest): + The request object. Request message for GetProperty RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{name=properties/*}', + }, + ] + request, metadata = self._interceptor.pre_get_property(request, metadata) + pb_request = analytics_admin.GetPropertyRequest.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 = resources.Property() + pb_resp = resources.Property.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_property(resp) + return resp + + class _ListAccounts(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListAccounts") + + def __call__(self, + request: analytics_admin.ListAccountsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListAccountsResponse: + r"""Call the list accounts method over HTTP. + + Args: + request (~.analytics_admin.ListAccountsRequest): + The request object. Request message for ListAccounts RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListAccountsResponse: + Request message for ListAccounts RPC. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/accounts', + }, + ] + request, metadata = self._interceptor.pre_list_accounts(request, metadata) + pb_request = analytics_admin.ListAccountsRequest.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 = analytics_admin.ListAccountsResponse() + pb_resp = analytics_admin.ListAccountsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_accounts(resp) + return resp + + class _ListAccountSummaries(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListAccountSummaries") + + def __call__(self, + request: analytics_admin.ListAccountSummariesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListAccountSummariesResponse: + r"""Call the list account summaries method over HTTP. + + Args: + request (~.analytics_admin.ListAccountSummariesRequest): + The request object. Request message for + ListAccountSummaries RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListAccountSummariesResponse: + Response message for + ListAccountSummaries RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/accountSummaries', + }, + ] + request, metadata = self._interceptor.pre_list_account_summaries(request, metadata) + pb_request = analytics_admin.ListAccountSummariesRequest.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 = analytics_admin.ListAccountSummariesResponse() + pb_resp = analytics_admin.ListAccountSummariesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_account_summaries(resp) + return resp + + class _ListConversionEvents(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListConversionEvents") + + __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: analytics_admin.ListConversionEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListConversionEventsResponse: + r"""Call the list conversion events method over HTTP. + + Args: + request (~.analytics_admin.ListConversionEventsRequest): + The request object. Request message for + ListConversionEvents RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListConversionEventsResponse: + Response message for + ListConversionEvents RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=properties/*}/conversionEvents', + }, + ] + request, metadata = self._interceptor.pre_list_conversion_events(request, metadata) + pb_request = analytics_admin.ListConversionEventsRequest.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 = analytics_admin.ListConversionEventsResponse() + pb_resp = analytics_admin.ListConversionEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_conversion_events(resp) + return resp + + class _ListCustomDimensions(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListCustomDimensions") + + __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: analytics_admin.ListCustomDimensionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListCustomDimensionsResponse: + r"""Call the list custom dimensions method over HTTP. + + Args: + request (~.analytics_admin.ListCustomDimensionsRequest): + The request object. Request message for + ListCustomDimensions RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListCustomDimensionsResponse: + Response message for + ListCustomDimensions RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=properties/*}/customDimensions', + }, + ] + request, metadata = self._interceptor.pre_list_custom_dimensions(request, metadata) + pb_request = analytics_admin.ListCustomDimensionsRequest.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 = analytics_admin.ListCustomDimensionsResponse() + pb_resp = analytics_admin.ListCustomDimensionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_custom_dimensions(resp) + return resp + + class _ListCustomMetrics(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListCustomMetrics") + + __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: analytics_admin.ListCustomMetricsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListCustomMetricsResponse: + r"""Call the list custom metrics method over HTTP. + + Args: + request (~.analytics_admin.ListCustomMetricsRequest): + The request object. Request message for ListCustomMetrics + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListCustomMetricsResponse: + Response message for + ListCustomMetrics RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=properties/*}/customMetrics', + }, + ] + request, metadata = self._interceptor.pre_list_custom_metrics(request, metadata) + pb_request = analytics_admin.ListCustomMetricsRequest.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 = analytics_admin.ListCustomMetricsResponse() + pb_resp = analytics_admin.ListCustomMetricsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_custom_metrics(resp) + return resp + + class _ListDataStreams(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListDataStreams") + + __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: analytics_admin.ListDataStreamsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListDataStreamsResponse: + r"""Call the list data streams method over HTTP. + + Args: + request (~.analytics_admin.ListDataStreamsRequest): + The request object. Request message for ListDataStreams + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListDataStreamsResponse: + Response message for ListDataStreams + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=properties/*}/dataStreams', + }, + ] + request, metadata = self._interceptor.pre_list_data_streams(request, metadata) + pb_request = analytics_admin.ListDataStreamsRequest.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 = analytics_admin.ListDataStreamsResponse() + pb_resp = analytics_admin.ListDataStreamsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_data_streams(resp) + return resp + + class _ListFirebaseLinks(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListFirebaseLinks") + + __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: analytics_admin.ListFirebaseLinksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListFirebaseLinksResponse: + r"""Call the list firebase links method over HTTP. + + Args: + request (~.analytics_admin.ListFirebaseLinksRequest): + The request object. Request message for ListFirebaseLinks + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListFirebaseLinksResponse: + Response message for + ListFirebaseLinks RPC + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=properties/*}/firebaseLinks', + }, + ] + request, metadata = self._interceptor.pre_list_firebase_links(request, metadata) + pb_request = analytics_admin.ListFirebaseLinksRequest.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 = analytics_admin.ListFirebaseLinksResponse() + pb_resp = analytics_admin.ListFirebaseLinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_firebase_links(resp) + return resp + + class _ListGoogleAdsLinks(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListGoogleAdsLinks") + + __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: analytics_admin.ListGoogleAdsLinksRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListGoogleAdsLinksResponse: + r"""Call the list google ads links method over HTTP. + + Args: + request (~.analytics_admin.ListGoogleAdsLinksRequest): + The request object. Request message for + ListGoogleAdsLinks RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListGoogleAdsLinksResponse: + Response message for + ListGoogleAdsLinks RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=properties/*}/googleAdsLinks', + }, + ] + request, metadata = self._interceptor.pre_list_google_ads_links(request, metadata) + pb_request = analytics_admin.ListGoogleAdsLinksRequest.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 = analytics_admin.ListGoogleAdsLinksResponse() + pb_resp = analytics_admin.ListGoogleAdsLinksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_google_ads_links(resp) + return resp + + class _ListKeyEvents(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListKeyEvents") + + __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: analytics_admin.ListKeyEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListKeyEventsResponse: + r"""Call the list key events method over HTTP. + + Args: + request (~.analytics_admin.ListKeyEventsRequest): + The request object. Request message for ListKeyEvents RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListKeyEventsResponse: + Response message for ListKeyEvents + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=properties/*}/keyEvents', + }, + ] + request, metadata = self._interceptor.pre_list_key_events(request, metadata) + pb_request = analytics_admin.ListKeyEventsRequest.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 = analytics_admin.ListKeyEventsResponse() + pb_resp = analytics_admin.ListKeyEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_key_events(resp) + return resp + + class _ListMeasurementProtocolSecrets(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListMeasurementProtocolSecrets") + + __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: analytics_admin.ListMeasurementProtocolSecretsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListMeasurementProtocolSecretsResponse: + r"""Call the list measurement protocol + secrets method over HTTP. + + Args: + request (~.analytics_admin.ListMeasurementProtocolSecretsRequest): + The request object. Request message for + ListMeasurementProtocolSecret RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListMeasurementProtocolSecretsResponse: + Response message for + ListMeasurementProtocolSecret RPC + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets', + }, + ] + request, metadata = self._interceptor.pre_list_measurement_protocol_secrets(request, metadata) + pb_request = analytics_admin.ListMeasurementProtocolSecretsRequest.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 = analytics_admin.ListMeasurementProtocolSecretsResponse() + pb_resp = analytics_admin.ListMeasurementProtocolSecretsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_measurement_protocol_secrets(resp) + return resp + + class _ListProperties(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ListProperties") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "filter" : "", } + + @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: analytics_admin.ListPropertiesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ListPropertiesResponse: + r"""Call the list properties method over HTTP. + + Args: + request (~.analytics_admin.ListPropertiesRequest): + The request object. Request message for ListProperties + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ListPropertiesResponse: + Response message for ListProperties + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1beta/properties', + }, + ] + request, metadata = self._interceptor.pre_list_properties(request, metadata) + pb_request = analytics_admin.ListPropertiesRequest.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 = analytics_admin.ListPropertiesResponse() + pb_resp = analytics_admin.ListPropertiesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_properties(resp) + return resp + + class _ProvisionAccountTicket(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("ProvisionAccountTicket") + + def __call__(self, + request: analytics_admin.ProvisionAccountTicketRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.ProvisionAccountTicketResponse: + r"""Call the provision account ticket method over HTTP. + + Args: + request (~.analytics_admin.ProvisionAccountTicketRequest): + The request object. Request message for + ProvisionAccountTicket RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.ProvisionAccountTicketResponse: + Response message for + ProvisionAccountTicket RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/accounts:provisionAccountTicket', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_provision_account_ticket(request, metadata) + pb_request = analytics_admin.ProvisionAccountTicketRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_admin.ProvisionAccountTicketResponse() + pb_resp = analytics_admin.ProvisionAccountTicketResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_provision_account_ticket(resp) + return resp + + class _RunAccessReport(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("RunAccessReport") + + def __call__(self, + request: analytics_admin.RunAccessReportRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.RunAccessReportResponse: + r"""Call the run access report method over HTTP. + + Args: + request (~.analytics_admin.RunAccessReportRequest): + The request object. The request for a Data Access Record + Report. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.RunAccessReportResponse: + The customized Data Access Record + Report response. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{entity=properties/*}:runAccessReport', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1beta/{entity=accounts/*}:runAccessReport', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_run_access_report(request, metadata) + pb_request = analytics_admin.RunAccessReportRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = analytics_admin.RunAccessReportResponse() + pb_resp = analytics_admin.RunAccessReportResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_run_access_report(resp) + return resp + + class _SearchChangeHistoryEvents(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("SearchChangeHistoryEvents") + + __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: analytics_admin.SearchChangeHistoryEventsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> analytics_admin.SearchChangeHistoryEventsResponse: + r"""Call the search change history + events method over HTTP. + + Args: + request (~.analytics_admin.SearchChangeHistoryEventsRequest): + The request object. Request message for + SearchChangeHistoryEvents RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.analytics_admin.SearchChangeHistoryEventsResponse: + Response message for SearchAccounts + RPC. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1beta/{account=accounts/*}:searchChangeHistoryEvents', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_search_change_history_events(request, metadata) + pb_request = analytics_admin.SearchChangeHistoryEventsRequest.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 = analytics_admin.SearchChangeHistoryEventsResponse() + pb_resp = analytics_admin.SearchChangeHistoryEventsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_change_history_events(resp) + return resp + + class _UpdateAccount(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateAccount") + + __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: analytics_admin.UpdateAccountRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Account: + r"""Call the update account method over HTTP. + + Args: + request (~.analytics_admin.UpdateAccountRequest): + The request object. Request message for UpdateAccount + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Account: + A resource message representing a + Google Analytics account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{account.name=accounts/*}', + 'body': 'account', + }, + ] + request, metadata = self._interceptor.pre_update_account(request, metadata) + pb_request = analytics_admin.UpdateAccountRequest.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 = resources.Account() + pb_resp = resources.Account.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_account(resp) + return resp + + class _UpdateConversionEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateConversionEvent") + + __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: analytics_admin.UpdateConversionEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ConversionEvent: + r"""Call the update conversion event method over HTTP. + + Args: + request (~.analytics_admin.UpdateConversionEventRequest): + The request object. Request message for + UpdateConversionEvent RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ConversionEvent: + A conversion event in a Google + Analytics property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{conversion_event.name=properties/*/conversionEvents/*}', + 'body': 'conversion_event', + }, + ] + request, metadata = self._interceptor.pre_update_conversion_event(request, metadata) + pb_request = analytics_admin.UpdateConversionEventRequest.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 = resources.ConversionEvent() + pb_resp = resources.ConversionEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_conversion_event(resp) + return resp + + class _UpdateCustomDimension(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateCustomDimension") + + __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: analytics_admin.UpdateCustomDimensionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomDimension: + r"""Call the update custom dimension method over HTTP. + + Args: + request (~.analytics_admin.UpdateCustomDimensionRequest): + The request object. Request message for + UpdateCustomDimension RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomDimension: + A definition for a CustomDimension. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{custom_dimension.name=properties/*/customDimensions/*}', + 'body': 'custom_dimension', + }, + ] + request, metadata = self._interceptor.pre_update_custom_dimension(request, metadata) + pb_request = analytics_admin.UpdateCustomDimensionRequest.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 = resources.CustomDimension() + pb_resp = resources.CustomDimension.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_custom_dimension(resp) + return resp + + class _UpdateCustomMetric(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateCustomMetric") + + __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: analytics_admin.UpdateCustomMetricRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CustomMetric: + r"""Call the update custom metric method over HTTP. + + Args: + request (~.analytics_admin.UpdateCustomMetricRequest): + The request object. Request message for + UpdateCustomMetric RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CustomMetric: + A definition for a custom metric. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{custom_metric.name=properties/*/customMetrics/*}', + 'body': 'custom_metric', + }, + ] + request, metadata = self._interceptor.pre_update_custom_metric(request, metadata) + pb_request = analytics_admin.UpdateCustomMetricRequest.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 = resources.CustomMetric() + pb_resp = resources.CustomMetric.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_custom_metric(resp) + return resp + + class _UpdateDataRetentionSettings(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateDataRetentionSettings") + + __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: analytics_admin.UpdateDataRetentionSettingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataRetentionSettings: + r"""Call the update data retention + settings method over HTTP. + + Args: + request (~.analytics_admin.UpdateDataRetentionSettingsRequest): + The request object. Request message for + UpdateDataRetentionSettings RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataRetentionSettings: + Settings values for data retention. + This is a singleton resource. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{data_retention_settings.name=properties/*/dataRetentionSettings}', + 'body': 'data_retention_settings', + }, + ] + request, metadata = self._interceptor.pre_update_data_retention_settings(request, metadata) + pb_request = analytics_admin.UpdateDataRetentionSettingsRequest.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 = resources.DataRetentionSettings() + pb_resp = resources.DataRetentionSettings.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_data_retention_settings(resp) + return resp + + class _UpdateDataStream(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateDataStream") + + __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: analytics_admin.UpdateDataStreamRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.DataStream: + r"""Call the update data stream method over HTTP. + + Args: + request (~.analytics_admin.UpdateDataStreamRequest): + The request object. Request message for UpdateDataStream + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.DataStream: + A resource message representing a + data stream. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{data_stream.name=properties/*/dataStreams/*}', + 'body': 'data_stream', + }, + ] + request, metadata = self._interceptor.pre_update_data_stream(request, metadata) + pb_request = analytics_admin.UpdateDataStreamRequest.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 = resources.DataStream() + pb_resp = resources.DataStream.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_data_stream(resp) + return resp + + class _UpdateGoogleAdsLink(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateGoogleAdsLink") + + __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: analytics_admin.UpdateGoogleAdsLinkRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.GoogleAdsLink: + r"""Call the update google ads link method over HTTP. + + Args: + request (~.analytics_admin.UpdateGoogleAdsLinkRequest): + The request object. Request message for + UpdateGoogleAdsLink RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.GoogleAdsLink: + A link between a GA4 property and a + Google Ads account. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{google_ads_link.name=properties/*/googleAdsLinks/*}', + 'body': 'google_ads_link', + }, + ] + request, metadata = self._interceptor.pre_update_google_ads_link(request, metadata) + pb_request = analytics_admin.UpdateGoogleAdsLinkRequest.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 = resources.GoogleAdsLink() + pb_resp = resources.GoogleAdsLink.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_google_ads_link(resp) + return resp + + class _UpdateKeyEvent(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateKeyEvent") + + __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: analytics_admin.UpdateKeyEventRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.KeyEvent: + r"""Call the update key event method over HTTP. + + Args: + request (~.analytics_admin.UpdateKeyEventRequest): + The request object. Request message for UpdateKeyEvent + RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.KeyEvent: + A key event in a Google Analytics + property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{key_event.name=properties/*/keyEvents/*}', + 'body': 'key_event', + }, + ] + request, metadata = self._interceptor.pre_update_key_event(request, metadata) + pb_request = analytics_admin.UpdateKeyEventRequest.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 = resources.KeyEvent() + pb_resp = resources.KeyEvent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_key_event(resp) + return resp + + class _UpdateMeasurementProtocolSecret(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateMeasurementProtocolSecret") + + __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: analytics_admin.UpdateMeasurementProtocolSecretRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.MeasurementProtocolSecret: + r"""Call the update measurement + protocol secret method over HTTP. + + Args: + request (~.analytics_admin.UpdateMeasurementProtocolSecretRequest): + The request object. Request message for + UpdateMeasurementProtocolSecret RPC + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.MeasurementProtocolSecret: + A secret value used for sending hits + to Measurement Protocol. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{measurement_protocol_secret.name=properties/*/dataStreams/*/measurementProtocolSecrets/*}', + 'body': 'measurement_protocol_secret', + }, + ] + request, metadata = self._interceptor.pre_update_measurement_protocol_secret(request, metadata) + pb_request = analytics_admin.UpdateMeasurementProtocolSecretRequest.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 = resources.MeasurementProtocolSecret() + pb_resp = resources.MeasurementProtocolSecret.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_measurement_protocol_secret(resp) + return resp + + class _UpdateProperty(AnalyticsAdminServiceRestStub): + def __hash__(self): + return hash("UpdateProperty") + + __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: analytics_admin.UpdatePropertyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.Property: + r"""Call the update property method over HTTP. + + Args: + request (~.analytics_admin.UpdatePropertyRequest): + The request object. Request message for UpdateProperty + RPC. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.Property: + A resource message representing a + Google Analytics GA4 property. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1beta/{property.name=properties/*}', + 'body': 'property', + }, + ] + request, metadata = self._interceptor.pre_update_property(request, metadata) + pb_request = analytics_admin.UpdatePropertyRequest.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 = resources.Property() + pb_resp = resources.Property.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_property(resp) + return resp + + @property + def acknowledge_user_data_collection(self) -> Callable[ + [analytics_admin.AcknowledgeUserDataCollectionRequest], + analytics_admin.AcknowledgeUserDataCollectionResponse]: + # 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._AcknowledgeUserDataCollection(self._session, self._host, self._interceptor) # type: ignore + + @property + def archive_custom_dimension(self) -> Callable[ + [analytics_admin.ArchiveCustomDimensionRequest], + 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._ArchiveCustomDimension(self._session, self._host, self._interceptor) # type: ignore + + @property + def archive_custom_metric(self) -> Callable[ + [analytics_admin.ArchiveCustomMetricRequest], + 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._ArchiveCustomMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_conversion_event(self) -> Callable[ + [analytics_admin.CreateConversionEventRequest], + resources.ConversionEvent]: + # 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._CreateConversionEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_custom_dimension(self) -> Callable[ + [analytics_admin.CreateCustomDimensionRequest], + resources.CustomDimension]: + # 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._CreateCustomDimension(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_custom_metric(self) -> Callable[ + [analytics_admin.CreateCustomMetricRequest], + resources.CustomMetric]: + # 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._CreateCustomMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_data_stream(self) -> Callable[ + [analytics_admin.CreateDataStreamRequest], + resources.DataStream]: + # 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._CreateDataStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_firebase_link(self) -> Callable[ + [analytics_admin.CreateFirebaseLinkRequest], + resources.FirebaseLink]: + # 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._CreateFirebaseLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_google_ads_link(self) -> Callable[ + [analytics_admin.CreateGoogleAdsLinkRequest], + resources.GoogleAdsLink]: + # 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._CreateGoogleAdsLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_key_event(self) -> Callable[ + [analytics_admin.CreateKeyEventRequest], + resources.KeyEvent]: + # 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._CreateKeyEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.CreateMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + # 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._CreateMeasurementProtocolSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_property(self) -> Callable[ + [analytics_admin.CreatePropertyRequest], + resources.Property]: + # 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._CreateProperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_account(self) -> Callable[ + [analytics_admin.DeleteAccountRequest], + 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._DeleteAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_conversion_event(self) -> Callable[ + [analytics_admin.DeleteConversionEventRequest], + 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._DeleteConversionEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_data_stream(self) -> Callable[ + [analytics_admin.DeleteDataStreamRequest], + 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._DeleteDataStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_firebase_link(self) -> Callable[ + [analytics_admin.DeleteFirebaseLinkRequest], + 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._DeleteFirebaseLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_google_ads_link(self) -> Callable[ + [analytics_admin.DeleteGoogleAdsLinkRequest], + 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._DeleteGoogleAdsLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_key_event(self) -> Callable[ + [analytics_admin.DeleteKeyEventRequest], + 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._DeleteKeyEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.DeleteMeasurementProtocolSecretRequest], + 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._DeleteMeasurementProtocolSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_property(self) -> Callable[ + [analytics_admin.DeletePropertyRequest], + resources.Property]: + # 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._DeleteProperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_account(self) -> Callable[ + [analytics_admin.GetAccountRequest], + resources.Account]: + # 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._GetAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_conversion_event(self) -> Callable[ + [analytics_admin.GetConversionEventRequest], + resources.ConversionEvent]: + # 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._GetConversionEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_dimension(self) -> Callable[ + [analytics_admin.GetCustomDimensionRequest], + resources.CustomDimension]: + # 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._GetCustomDimension(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_custom_metric(self) -> Callable[ + [analytics_admin.GetCustomMetricRequest], + resources.CustomMetric]: + # 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._GetCustomMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_retention_settings(self) -> Callable[ + [analytics_admin.GetDataRetentionSettingsRequest], + resources.DataRetentionSettings]: + # 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._GetDataRetentionSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_sharing_settings(self) -> Callable[ + [analytics_admin.GetDataSharingSettingsRequest], + resources.DataSharingSettings]: + # 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._GetDataSharingSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_data_stream(self) -> Callable[ + [analytics_admin.GetDataStreamRequest], + resources.DataStream]: + # 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._GetDataStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_key_event(self) -> Callable[ + [analytics_admin.GetKeyEventRequest], + resources.KeyEvent]: + # 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._GetKeyEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.GetMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + # 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._GetMeasurementProtocolSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_property(self) -> Callable[ + [analytics_admin.GetPropertyRequest], + resources.Property]: + # 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._GetProperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_accounts(self) -> Callable[ + [analytics_admin.ListAccountsRequest], + analytics_admin.ListAccountsResponse]: + # 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._ListAccounts(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_account_summaries(self) -> Callable[ + [analytics_admin.ListAccountSummariesRequest], + analytics_admin.ListAccountSummariesResponse]: + # 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._ListAccountSummaries(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_conversion_events(self) -> Callable[ + [analytics_admin.ListConversionEventsRequest], + analytics_admin.ListConversionEventsResponse]: + # 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._ListConversionEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_dimensions(self) -> Callable[ + [analytics_admin.ListCustomDimensionsRequest], + analytics_admin.ListCustomDimensionsResponse]: + # 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._ListCustomDimensions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_custom_metrics(self) -> Callable[ + [analytics_admin.ListCustomMetricsRequest], + analytics_admin.ListCustomMetricsResponse]: + # 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._ListCustomMetrics(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_data_streams(self) -> Callable[ + [analytics_admin.ListDataStreamsRequest], + analytics_admin.ListDataStreamsResponse]: + # 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._ListDataStreams(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_firebase_links(self) -> Callable[ + [analytics_admin.ListFirebaseLinksRequest], + analytics_admin.ListFirebaseLinksResponse]: + # 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._ListFirebaseLinks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_google_ads_links(self) -> Callable[ + [analytics_admin.ListGoogleAdsLinksRequest], + analytics_admin.ListGoogleAdsLinksResponse]: + # 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._ListGoogleAdsLinks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_key_events(self) -> Callable[ + [analytics_admin.ListKeyEventsRequest], + analytics_admin.ListKeyEventsResponse]: + # 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._ListKeyEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_measurement_protocol_secrets(self) -> Callable[ + [analytics_admin.ListMeasurementProtocolSecretsRequest], + analytics_admin.ListMeasurementProtocolSecretsResponse]: + # 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._ListMeasurementProtocolSecrets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_properties(self) -> Callable[ + [analytics_admin.ListPropertiesRequest], + analytics_admin.ListPropertiesResponse]: + # 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._ListProperties(self._session, self._host, self._interceptor) # type: ignore + + @property + def provision_account_ticket(self) -> Callable[ + [analytics_admin.ProvisionAccountTicketRequest], + analytics_admin.ProvisionAccountTicketResponse]: + # 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._ProvisionAccountTicket(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_access_report(self) -> Callable[ + [analytics_admin.RunAccessReportRequest], + analytics_admin.RunAccessReportResponse]: + # 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._RunAccessReport(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_change_history_events(self) -> Callable[ + [analytics_admin.SearchChangeHistoryEventsRequest], + analytics_admin.SearchChangeHistoryEventsResponse]: + # 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._SearchChangeHistoryEvents(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_account(self) -> Callable[ + [analytics_admin.UpdateAccountRequest], + resources.Account]: + # 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._UpdateAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_conversion_event(self) -> Callable[ + [analytics_admin.UpdateConversionEventRequest], + resources.ConversionEvent]: + # 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._UpdateConversionEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_dimension(self) -> Callable[ + [analytics_admin.UpdateCustomDimensionRequest], + resources.CustomDimension]: + # 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._UpdateCustomDimension(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_custom_metric(self) -> Callable[ + [analytics_admin.UpdateCustomMetricRequest], + resources.CustomMetric]: + # 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._UpdateCustomMetric(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_retention_settings(self) -> Callable[ + [analytics_admin.UpdateDataRetentionSettingsRequest], + resources.DataRetentionSettings]: + # 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._UpdateDataRetentionSettings(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_data_stream(self) -> Callable[ + [analytics_admin.UpdateDataStreamRequest], + resources.DataStream]: + # 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._UpdateDataStream(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_google_ads_link(self) -> Callable[ + [analytics_admin.UpdateGoogleAdsLinkRequest], + resources.GoogleAdsLink]: + # 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._UpdateGoogleAdsLink(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_key_event(self) -> Callable[ + [analytics_admin.UpdateKeyEventRequest], + resources.KeyEvent]: + # 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._UpdateKeyEvent(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_measurement_protocol_secret(self) -> Callable[ + [analytics_admin.UpdateMeasurementProtocolSecretRequest], + resources.MeasurementProtocolSecret]: + # 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._UpdateMeasurementProtocolSecret(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_property(self) -> Callable[ + [analytics_admin.UpdatePropertyRequest], + resources.Property]: + # 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._UpdateProperty(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AnalyticsAdminServiceRestTransport', +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/__init__.py new file mode 100644 index 000000000000..82d03aa543b5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/__init__.py @@ -0,0 +1,244 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .access_report import ( + AccessBetweenFilter, + AccessDateRange, + AccessDimension, + AccessDimensionHeader, + AccessDimensionValue, + AccessFilter, + AccessFilterExpression, + AccessFilterExpressionList, + AccessInListFilter, + AccessMetric, + AccessMetricHeader, + AccessMetricValue, + AccessNumericFilter, + AccessOrderBy, + AccessQuota, + AccessQuotaStatus, + AccessRow, + AccessStringFilter, + NumericValue, +) +from .analytics_admin import ( + AcknowledgeUserDataCollectionRequest, + AcknowledgeUserDataCollectionResponse, + ArchiveCustomDimensionRequest, + ArchiveCustomMetricRequest, + CreateConversionEventRequest, + CreateCustomDimensionRequest, + CreateCustomMetricRequest, + CreateDataStreamRequest, + CreateFirebaseLinkRequest, + CreateGoogleAdsLinkRequest, + CreateKeyEventRequest, + CreateMeasurementProtocolSecretRequest, + CreatePropertyRequest, + DeleteAccountRequest, + DeleteConversionEventRequest, + DeleteDataStreamRequest, + DeleteFirebaseLinkRequest, + DeleteGoogleAdsLinkRequest, + DeleteKeyEventRequest, + DeleteMeasurementProtocolSecretRequest, + DeletePropertyRequest, + GetAccountRequest, + GetConversionEventRequest, + GetCustomDimensionRequest, + GetCustomMetricRequest, + GetDataRetentionSettingsRequest, + GetDataSharingSettingsRequest, + GetDataStreamRequest, + GetKeyEventRequest, + GetMeasurementProtocolSecretRequest, + GetPropertyRequest, + ListAccountsRequest, + ListAccountsResponse, + ListAccountSummariesRequest, + ListAccountSummariesResponse, + ListConversionEventsRequest, + ListConversionEventsResponse, + ListCustomDimensionsRequest, + ListCustomDimensionsResponse, + ListCustomMetricsRequest, + ListCustomMetricsResponse, + ListDataStreamsRequest, + ListDataStreamsResponse, + ListFirebaseLinksRequest, + ListFirebaseLinksResponse, + ListGoogleAdsLinksRequest, + ListGoogleAdsLinksResponse, + ListKeyEventsRequest, + ListKeyEventsResponse, + ListMeasurementProtocolSecretsRequest, + ListMeasurementProtocolSecretsResponse, + ListPropertiesRequest, + ListPropertiesResponse, + ProvisionAccountTicketRequest, + ProvisionAccountTicketResponse, + RunAccessReportRequest, + RunAccessReportResponse, + SearchChangeHistoryEventsRequest, + SearchChangeHistoryEventsResponse, + UpdateAccountRequest, + UpdateConversionEventRequest, + UpdateCustomDimensionRequest, + UpdateCustomMetricRequest, + UpdateDataRetentionSettingsRequest, + UpdateDataStreamRequest, + UpdateGoogleAdsLinkRequest, + UpdateKeyEventRequest, + UpdateMeasurementProtocolSecretRequest, + UpdatePropertyRequest, +) +from .resources import ( + Account, + AccountSummary, + ChangeHistoryChange, + ChangeHistoryEvent, + ConversionEvent, + CustomDimension, + CustomMetric, + DataRetentionSettings, + DataSharingSettings, + DataStream, + FirebaseLink, + GoogleAdsLink, + KeyEvent, + MeasurementProtocolSecret, + Property, + PropertySummary, + ActionType, + ActorType, + ChangeHistoryResourceType, + IndustryCategory, + PropertyType, + ServiceLevel, +) + +__all__ = ( + 'AccessBetweenFilter', + 'AccessDateRange', + 'AccessDimension', + 'AccessDimensionHeader', + 'AccessDimensionValue', + 'AccessFilter', + 'AccessFilterExpression', + 'AccessFilterExpressionList', + 'AccessInListFilter', + 'AccessMetric', + 'AccessMetricHeader', + 'AccessMetricValue', + 'AccessNumericFilter', + 'AccessOrderBy', + 'AccessQuota', + 'AccessQuotaStatus', + 'AccessRow', + 'AccessStringFilter', + 'NumericValue', + 'AcknowledgeUserDataCollectionRequest', + 'AcknowledgeUserDataCollectionResponse', + 'ArchiveCustomDimensionRequest', + 'ArchiveCustomMetricRequest', + 'CreateConversionEventRequest', + 'CreateCustomDimensionRequest', + 'CreateCustomMetricRequest', + 'CreateDataStreamRequest', + 'CreateFirebaseLinkRequest', + 'CreateGoogleAdsLinkRequest', + 'CreateKeyEventRequest', + 'CreateMeasurementProtocolSecretRequest', + 'CreatePropertyRequest', + 'DeleteAccountRequest', + 'DeleteConversionEventRequest', + 'DeleteDataStreamRequest', + 'DeleteFirebaseLinkRequest', + 'DeleteGoogleAdsLinkRequest', + 'DeleteKeyEventRequest', + 'DeleteMeasurementProtocolSecretRequest', + 'DeletePropertyRequest', + 'GetAccountRequest', + 'GetConversionEventRequest', + 'GetCustomDimensionRequest', + 'GetCustomMetricRequest', + 'GetDataRetentionSettingsRequest', + 'GetDataSharingSettingsRequest', + 'GetDataStreamRequest', + 'GetKeyEventRequest', + 'GetMeasurementProtocolSecretRequest', + 'GetPropertyRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'ListAccountSummariesRequest', + 'ListAccountSummariesResponse', + 'ListConversionEventsRequest', + 'ListConversionEventsResponse', + 'ListCustomDimensionsRequest', + 'ListCustomDimensionsResponse', + 'ListCustomMetricsRequest', + 'ListCustomMetricsResponse', + 'ListDataStreamsRequest', + 'ListDataStreamsResponse', + 'ListFirebaseLinksRequest', + 'ListFirebaseLinksResponse', + 'ListGoogleAdsLinksRequest', + 'ListGoogleAdsLinksResponse', + 'ListKeyEventsRequest', + 'ListKeyEventsResponse', + 'ListMeasurementProtocolSecretsRequest', + 'ListMeasurementProtocolSecretsResponse', + 'ListPropertiesRequest', + 'ListPropertiesResponse', + 'ProvisionAccountTicketRequest', + 'ProvisionAccountTicketResponse', + 'RunAccessReportRequest', + 'RunAccessReportResponse', + 'SearchChangeHistoryEventsRequest', + 'SearchChangeHistoryEventsResponse', + 'UpdateAccountRequest', + 'UpdateConversionEventRequest', + 'UpdateCustomDimensionRequest', + 'UpdateCustomMetricRequest', + 'UpdateDataRetentionSettingsRequest', + 'UpdateDataStreamRequest', + 'UpdateGoogleAdsLinkRequest', + 'UpdateKeyEventRequest', + 'UpdateMeasurementProtocolSecretRequest', + 'UpdatePropertyRequest', + 'Account', + 'AccountSummary', + 'ChangeHistoryChange', + 'ChangeHistoryEvent', + 'ConversionEvent', + 'CustomDimension', + 'CustomMetric', + 'DataRetentionSettings', + 'DataSharingSettings', + 'DataStream', + 'FirebaseLink', + 'GoogleAdsLink', + 'KeyEvent', + 'MeasurementProtocolSecret', + 'Property', + 'PropertySummary', + 'ActionType', + 'ActorType', + 'ChangeHistoryResourceType', + 'IndustryCategory', + 'PropertyType', + 'ServiceLevel', +) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/access_report.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/access_report.py new file mode 100644 index 000000000000..3e9bdd0073c3 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/access_report.py @@ -0,0 +1,703 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin.v1beta', + manifest={ + 'AccessDimension', + 'AccessMetric', + 'AccessDateRange', + 'AccessFilterExpression', + 'AccessFilterExpressionList', + 'AccessFilter', + 'AccessStringFilter', + 'AccessInListFilter', + 'AccessNumericFilter', + 'AccessBetweenFilter', + 'NumericValue', + 'AccessOrderBy', + 'AccessDimensionHeader', + 'AccessMetricHeader', + 'AccessRow', + 'AccessDimensionValue', + 'AccessMetricValue', + 'AccessQuota', + 'AccessQuotaStatus', + }, +) + + +class AccessDimension(proto.Message): + r"""Dimensions are attributes of your data. For example, the dimension + ``userEmail`` indicates the email of the user that accessed + reporting data. Dimension values in report responses are strings. + + Attributes: + dimension_name (str): + The API name of the dimension. See `Data Access + Schema `__ + for the list of dimensions supported in this API. + + Dimensions are referenced by name in ``dimensionFilter`` and + ``orderBys``. + """ + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessMetric(proto.Message): + r"""The quantitative measurements of a report. For example, the metric + ``accessCount`` is the total number of data access records. + + Attributes: + metric_name (str): + The API name of the metric. See `Data Access + Schema `__ + for the list of metrics supported in this API. + + Metrics are referenced by name in ``metricFilter`` & + ``orderBys``. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessDateRange(proto.Message): + r"""A contiguous range of days: startDate, startDate + 1, ..., + endDate. + + Attributes: + start_date (str): + The inclusive start date for the query in the format + ``YYYY-MM-DD``. Cannot be after ``endDate``. The format + ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, + and in that case, the date is inferred based on the current + time in the request's time zone. + end_date (str): + The inclusive end date for the query in the format + ``YYYY-MM-DD``. Cannot be before ``startDate``. The format + ``NdaysAgo``, ``yesterday``, or ``today`` is also accepted, + and in that case, the date is inferred based on the current + time in the request's time zone. + """ + + start_date: str = proto.Field( + proto.STRING, + number=1, + ) + end_date: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AccessFilterExpression(proto.Message): + r"""Expresses dimension or metric filters. The fields in the same + expression need to be either all dimensions or all metrics. + + 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: + and_group (google.analytics.admin_v1beta.types.AccessFilterExpressionList): + Each of the FilterExpressions in the and_group has an AND + relationship. + + This field is a member of `oneof`_ ``one_expression``. + or_group (google.analytics.admin_v1beta.types.AccessFilterExpressionList): + Each of the FilterExpressions in the or_group has an OR + relationship. + + This field is a member of `oneof`_ ``one_expression``. + not_expression (google.analytics.admin_v1beta.types.AccessFilterExpression): + The FilterExpression is NOT of not_expression. + + This field is a member of `oneof`_ ``one_expression``. + access_filter (google.analytics.admin_v1beta.types.AccessFilter): + A primitive filter. In the same + FilterExpression, all of the filter's field + names need to be either all dimensions or all + metrics. + + This field is a member of `oneof`_ ``one_expression``. + """ + + and_group: 'AccessFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=1, + oneof='one_expression', + message='AccessFilterExpressionList', + ) + or_group: 'AccessFilterExpressionList' = proto.Field( + proto.MESSAGE, + number=2, + oneof='one_expression', + message='AccessFilterExpressionList', + ) + not_expression: 'AccessFilterExpression' = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_expression', + message='AccessFilterExpression', + ) + access_filter: 'AccessFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_expression', + message='AccessFilter', + ) + + +class AccessFilterExpressionList(proto.Message): + r"""A list of filter expressions. + + Attributes: + expressions (MutableSequence[google.analytics.admin_v1beta.types.AccessFilterExpression]): + A list of filter expressions. + """ + + expressions: MutableSequence['AccessFilterExpression'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AccessFilterExpression', + ) + + +class AccessFilter(proto.Message): + r"""An expression to filter dimension or metric values. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + string_filter (google.analytics.admin_v1beta.types.AccessStringFilter): + Strings related filter. + + This field is a member of `oneof`_ ``one_filter``. + in_list_filter (google.analytics.admin_v1beta.types.AccessInListFilter): + A filter for in list values. + + This field is a member of `oneof`_ ``one_filter``. + numeric_filter (google.analytics.admin_v1beta.types.AccessNumericFilter): + A filter for numeric or date values. + + This field is a member of `oneof`_ ``one_filter``. + between_filter (google.analytics.admin_v1beta.types.AccessBetweenFilter): + A filter for two values. + + This field is a member of `oneof`_ ``one_filter``. + field_name (str): + The dimension name or metric name. + """ + + string_filter: 'AccessStringFilter' = proto.Field( + proto.MESSAGE, + number=2, + oneof='one_filter', + message='AccessStringFilter', + ) + in_list_filter: 'AccessInListFilter' = proto.Field( + proto.MESSAGE, + number=3, + oneof='one_filter', + message='AccessInListFilter', + ) + numeric_filter: 'AccessNumericFilter' = proto.Field( + proto.MESSAGE, + number=4, + oneof='one_filter', + message='AccessNumericFilter', + ) + between_filter: 'AccessBetweenFilter' = proto.Field( + proto.MESSAGE, + number=5, + oneof='one_filter', + message='AccessBetweenFilter', + ) + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessStringFilter(proto.Message): + r"""The filter for strings. + + Attributes: + match_type (google.analytics.admin_v1beta.types.AccessStringFilter.MatchType): + The match type for this filter. + value (str): + The string value used for the matching. + case_sensitive (bool): + If true, the string value is case sensitive. + """ + class MatchType(proto.Enum): + r"""The match type of a string filter. + + Values: + MATCH_TYPE_UNSPECIFIED (0): + Unspecified + EXACT (1): + Exact match of the string value. + BEGINS_WITH (2): + Begins with the string value. + ENDS_WITH (3): + Ends with the string value. + CONTAINS (4): + Contains the string value. + FULL_REGEXP (5): + Full match for the regular expression with + the string value. + PARTIAL_REGEXP (6): + Partial match for the regular expression with + the string value. + """ + MATCH_TYPE_UNSPECIFIED = 0 + EXACT = 1 + BEGINS_WITH = 2 + ENDS_WITH = 3 + CONTAINS = 4 + FULL_REGEXP = 5 + PARTIAL_REGEXP = 6 + + match_type: MatchType = proto.Field( + proto.ENUM, + number=1, + enum=MatchType, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class AccessInListFilter(proto.Message): + r"""The result needs to be in a list of string values. + + Attributes: + values (MutableSequence[str]): + The list of string values. Must be non-empty. + case_sensitive (bool): + If true, the string value is case sensitive. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + case_sensitive: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class AccessNumericFilter(proto.Message): + r"""Filters for numeric or date values. + + Attributes: + operation (google.analytics.admin_v1beta.types.AccessNumericFilter.Operation): + The operation type for this filter. + value (google.analytics.admin_v1beta.types.NumericValue): + A numeric value or a date value. + """ + class Operation(proto.Enum): + r"""The operation applied to a numeric filter. + + Values: + OPERATION_UNSPECIFIED (0): + Unspecified. + EQUAL (1): + Equal + LESS_THAN (2): + Less than + LESS_THAN_OR_EQUAL (3): + Less than or equal + GREATER_THAN (4): + Greater than + GREATER_THAN_OR_EQUAL (5): + Greater than or equal + """ + OPERATION_UNSPECIFIED = 0 + EQUAL = 1 + LESS_THAN = 2 + LESS_THAN_OR_EQUAL = 3 + GREATER_THAN = 4 + GREATER_THAN_OR_EQUAL = 5 + + operation: Operation = proto.Field( + proto.ENUM, + number=1, + enum=Operation, + ) + value: 'NumericValue' = proto.Field( + proto.MESSAGE, + number=2, + message='NumericValue', + ) + + +class AccessBetweenFilter(proto.Message): + r"""To express that the result needs to be between two numbers + (inclusive). + + Attributes: + from_value (google.analytics.admin_v1beta.types.NumericValue): + Begins with this number. + to_value (google.analytics.admin_v1beta.types.NumericValue): + Ends with this number. + """ + + from_value: 'NumericValue' = proto.Field( + proto.MESSAGE, + number=1, + message='NumericValue', + ) + to_value: 'NumericValue' = proto.Field( + proto.MESSAGE, + number=2, + message='NumericValue', + ) + + +class NumericValue(proto.Message): + r"""To represent a number. + + 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: + int64_value (int): + Integer value + + This field is a member of `oneof`_ ``one_value``. + double_value (float): + Double value + + This field is a member of `oneof`_ ``one_value``. + """ + + int64_value: int = proto.Field( + proto.INT64, + number=1, + oneof='one_value', + ) + double_value: float = proto.Field( + proto.DOUBLE, + number=2, + oneof='one_value', + ) + + +class AccessOrderBy(proto.Message): + r"""Order bys define how rows will be sorted in the response. For + example, ordering rows by descending access count is one + ordering, and ordering rows by the country string is a different + ordering. + + 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: + metric (google.analytics.admin_v1beta.types.AccessOrderBy.MetricOrderBy): + Sorts results by a metric's values. + + This field is a member of `oneof`_ ``one_order_by``. + dimension (google.analytics.admin_v1beta.types.AccessOrderBy.DimensionOrderBy): + Sorts results by a dimension's values. + + This field is a member of `oneof`_ ``one_order_by``. + desc (bool): + If true, sorts by descending order. If false + or unspecified, sorts in ascending order. + """ + + class MetricOrderBy(proto.Message): + r"""Sorts by metric values. + + Attributes: + metric_name (str): + A metric name in the request to order by. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class DimensionOrderBy(proto.Message): + r"""Sorts by dimension values. + + Attributes: + dimension_name (str): + A dimension name in the request to order by. + order_type (google.analytics.admin_v1beta.types.AccessOrderBy.DimensionOrderBy.OrderType): + Controls the rule for dimension value + ordering. + """ + class OrderType(proto.Enum): + r"""Rule to order the string dimension values by. + + Values: + ORDER_TYPE_UNSPECIFIED (0): + Unspecified. + ALPHANUMERIC (1): + Alphanumeric sort by Unicode code point. For + example, "2" < "A" < "X" < "b" < "z". + CASE_INSENSITIVE_ALPHANUMERIC (2): + Case insensitive alphanumeric sort by lower + case Unicode code point. For example, "2" < "A" + < "b" < "X" < "z". + NUMERIC (3): + Dimension values are converted to numbers before sorting. + For example in NUMERIC sort, "25" < "100", and in + ``ALPHANUMERIC`` sort, "100" < "25". Non-numeric dimension + values all have equal ordering value below all numeric + values. + """ + ORDER_TYPE_UNSPECIFIED = 0 + ALPHANUMERIC = 1 + CASE_INSENSITIVE_ALPHANUMERIC = 2 + NUMERIC = 3 + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + order_type: 'AccessOrderBy.DimensionOrderBy.OrderType' = proto.Field( + proto.ENUM, + number=2, + enum='AccessOrderBy.DimensionOrderBy.OrderType', + ) + + metric: MetricOrderBy = proto.Field( + proto.MESSAGE, + number=1, + oneof='one_order_by', + message=MetricOrderBy, + ) + dimension: DimensionOrderBy = proto.Field( + proto.MESSAGE, + number=2, + oneof='one_order_by', + message=DimensionOrderBy, + ) + desc: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class AccessDimensionHeader(proto.Message): + r"""Describes a dimension column in the report. Dimensions + requested in a report produce column entries within rows and + DimensionHeaders. However, dimensions used exclusively within + filters or expressions do not produce columns in a report; + correspondingly, those dimensions do not produce headers. + + Attributes: + dimension_name (str): + The dimension's name; for example + 'userEmail'. + """ + + dimension_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessMetricHeader(proto.Message): + r"""Describes a metric column in the report. Visible metrics + requested in a report produce column entries within rows and + MetricHeaders. However, metrics used exclusively within filters + or expressions do not produce columns in a report; + correspondingly, those metrics do not produce headers. + + Attributes: + metric_name (str): + The metric's name; for example 'accessCount'. + """ + + metric_name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessRow(proto.Message): + r"""Access report data for each row. + + Attributes: + dimension_values (MutableSequence[google.analytics.admin_v1beta.types.AccessDimensionValue]): + List of dimension values. These values are in + the same order as specified in the request. + metric_values (MutableSequence[google.analytics.admin_v1beta.types.AccessMetricValue]): + List of metric values. These values are in + the same order as specified in the request. + """ + + dimension_values: MutableSequence['AccessDimensionValue'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='AccessDimensionValue', + ) + metric_values: MutableSequence['AccessMetricValue'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AccessMetricValue', + ) + + +class AccessDimensionValue(proto.Message): + r"""The value of a dimension. + + Attributes: + value (str): + The dimension value. For example, this value + may be 'France' for the 'country' dimension. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessMetricValue(proto.Message): + r"""The value of a metric. + + Attributes: + value (str): + The measurement value. For example, this + value may be '13'. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AccessQuota(proto.Message): + r"""Current state of all quotas for this Analytics property. If + any quota for a property is exhausted, all requests to that + property will return Resource Exhausted errors. + + Attributes: + tokens_per_day (google.analytics.admin_v1beta.types.AccessQuotaStatus): + Properties can use 250,000 tokens per day. + Most requests consume fewer than 10 tokens. + tokens_per_hour (google.analytics.admin_v1beta.types.AccessQuotaStatus): + Properties can use 50,000 tokens per hour. An + API request consumes a single number of tokens, + and that number is deducted from all of the + hourly, daily, and per project hourly quotas. + concurrent_requests (google.analytics.admin_v1beta.types.AccessQuotaStatus): + Properties can use up to 50 concurrent + requests. + server_errors_per_project_per_hour (google.analytics.admin_v1beta.types.AccessQuotaStatus): + Properties and cloud project pairs can have + up to 50 server errors per hour. + tokens_per_project_per_hour (google.analytics.admin_v1beta.types.AccessQuotaStatus): + Properties can use up to 25% of their tokens + per project per hour. This amounts to Analytics + 360 Properties can use 12,500 tokens per project + per hour. An API request consumes a single + number of tokens, and that number is deducted + from all of the hourly, daily, and per project + hourly quotas. + """ + + tokens_per_day: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=1, + message='AccessQuotaStatus', + ) + tokens_per_hour: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=2, + message='AccessQuotaStatus', + ) + concurrent_requests: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=3, + message='AccessQuotaStatus', + ) + server_errors_per_project_per_hour: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=4, + message='AccessQuotaStatus', + ) + tokens_per_project_per_hour: 'AccessQuotaStatus' = proto.Field( + proto.MESSAGE, + number=5, + message='AccessQuotaStatus', + ) + + +class AccessQuotaStatus(proto.Message): + r"""Current state for a particular quota group. + + Attributes: + consumed (int): + Quota consumed by this request. + remaining (int): + Quota remaining after this request. + """ + + consumed: int = proto.Field( + proto.INT32, + number=1, + ) + remaining: int = proto.Field( + proto.INT32, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/analytics_admin.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/analytics_admin.py new file mode 100644 index 000000000000..05193f29d354 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/analytics_admin.py @@ -0,0 +1,1994 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1beta.types import access_report +from google.analytics.admin_v1beta.types import resources +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.analytics.admin.v1beta', + manifest={ + 'RunAccessReportRequest', + 'RunAccessReportResponse', + 'GetAccountRequest', + 'ListAccountsRequest', + 'ListAccountsResponse', + 'DeleteAccountRequest', + 'UpdateAccountRequest', + 'ProvisionAccountTicketRequest', + 'ProvisionAccountTicketResponse', + 'GetPropertyRequest', + 'ListPropertiesRequest', + 'ListPropertiesResponse', + 'UpdatePropertyRequest', + 'CreatePropertyRequest', + 'DeletePropertyRequest', + 'CreateFirebaseLinkRequest', + 'DeleteFirebaseLinkRequest', + 'ListFirebaseLinksRequest', + 'ListFirebaseLinksResponse', + 'CreateGoogleAdsLinkRequest', + 'UpdateGoogleAdsLinkRequest', + 'DeleteGoogleAdsLinkRequest', + 'ListGoogleAdsLinksRequest', + 'ListGoogleAdsLinksResponse', + 'GetDataSharingSettingsRequest', + 'ListAccountSummariesRequest', + 'ListAccountSummariesResponse', + 'AcknowledgeUserDataCollectionRequest', + 'AcknowledgeUserDataCollectionResponse', + 'SearchChangeHistoryEventsRequest', + 'SearchChangeHistoryEventsResponse', + 'GetMeasurementProtocolSecretRequest', + 'CreateMeasurementProtocolSecretRequest', + 'DeleteMeasurementProtocolSecretRequest', + 'UpdateMeasurementProtocolSecretRequest', + 'ListMeasurementProtocolSecretsRequest', + 'ListMeasurementProtocolSecretsResponse', + 'CreateConversionEventRequest', + 'UpdateConversionEventRequest', + 'GetConversionEventRequest', + 'DeleteConversionEventRequest', + 'ListConversionEventsRequest', + 'ListConversionEventsResponse', + 'CreateKeyEventRequest', + 'UpdateKeyEventRequest', + 'GetKeyEventRequest', + 'DeleteKeyEventRequest', + 'ListKeyEventsRequest', + 'ListKeyEventsResponse', + 'CreateCustomDimensionRequest', + 'UpdateCustomDimensionRequest', + 'ListCustomDimensionsRequest', + 'ListCustomDimensionsResponse', + 'ArchiveCustomDimensionRequest', + 'GetCustomDimensionRequest', + 'CreateCustomMetricRequest', + 'UpdateCustomMetricRequest', + 'ListCustomMetricsRequest', + 'ListCustomMetricsResponse', + 'ArchiveCustomMetricRequest', + 'GetCustomMetricRequest', + 'GetDataRetentionSettingsRequest', + 'UpdateDataRetentionSettingsRequest', + 'CreateDataStreamRequest', + 'DeleteDataStreamRequest', + 'UpdateDataStreamRequest', + 'ListDataStreamsRequest', + 'ListDataStreamsResponse', + 'GetDataStreamRequest', + }, +) + + +class RunAccessReportRequest(proto.Message): + r"""The request for a Data Access Record Report. + + Attributes: + entity (str): + The Data Access Report supports requesting at + the property level or account level. If + requested at the account level, Data Access + Reports include all access for all properties + under that account. + + To request at the property level, entity should + be for example 'properties/123' if "123" is your + GA4 property ID. To request at the account + level, entity should be for example + 'accounts/1234' if "1234" is your GA4 Account + ID. + dimensions (MutableSequence[google.analytics.admin_v1beta.types.AccessDimension]): + The dimensions requested and displayed in the + response. Requests are allowed up to 9 + dimensions. + metrics (MutableSequence[google.analytics.admin_v1beta.types.AccessMetric]): + The metrics requested and displayed in the + response. Requests are allowed up to 10 metrics. + date_ranges (MutableSequence[google.analytics.admin_v1beta.types.AccessDateRange]): + Date ranges of access records to read. If + multiple date ranges are requested, each + response row will contain a zero based date + range index. If two date ranges overlap, the + access records for the overlapping days is + included in the response rows for both date + ranges. Requests are allowed up to 2 date + ranges. + dimension_filter (google.analytics.admin_v1beta.types.AccessFilterExpression): + Dimension filters let you restrict report response to + specific dimension values which match the filter. For + example, filtering on access records of a single user. To + learn more, see `Fundamentals of Dimension + Filters `__ + for examples. Metrics cannot be used in this filter. + metric_filter (google.analytics.admin_v1beta.types.AccessFilterExpression): + Metric filters allow you to restrict report + response to specific metric values which match + the filter. Metric filters are applied after + aggregating the report's rows, similar to SQL + having-clause. Dimensions cannot be used in this + filter. + offset (int): + The row count of the start row. The first row is counted as + row 0. If offset is unspecified, it is treated as 0. If + offset is zero, then this method will return the first page + of results with ``limit`` entries. + + To learn more about this pagination parameter, see + `Pagination `__. + limit (int): + The number of rows to return. If unspecified, 10,000 rows + are returned. The API returns a maximum of 100,000 rows per + request, no matter how many you ask for. ``limit`` must be + positive. + + The API may return fewer rows than the requested ``limit``, + if there aren't as many remaining rows as the ``limit``. For + instance, there are fewer than 300 possible values for the + dimension ``country``, so when reporting on only + ``country``, you can't get more than 300 rows, even if you + set ``limit`` to a higher value. + + To learn more about this pagination parameter, see + `Pagination `__. + time_zone (str): + This request's time zone if specified. If unspecified, the + property's time zone is used. The request's time zone is + used to interpret the start & end dates of the report. + + Formatted as strings from the IANA Time Zone database + (https://www.iana.org/time-zones); for example + "America/New_York" or "Asia/Tokyo". + order_bys (MutableSequence[google.analytics.admin_v1beta.types.AccessOrderBy]): + Specifies how rows are ordered in the + response. + return_entity_quota (bool): + Toggles whether to return the current state of this + Analytics Property's quota. Quota is returned in + `AccessQuota <#AccessQuota>`__. For account-level requests, + this field must be false. + include_all_users (bool): + Optional. Determines whether to include users + who have never made an API call in the response. + If true, all users with access to the specified + property or account are included in the + response, regardless of whether they have made + an API call or not. If false, only the users who + have made an API call will be included. + expand_groups (bool): + Optional. Decides whether to return the users within user + groups. This field works only when include_all_users is set + to true. If true, it will return all users with access to + the specified property or account. If false, only the users + with direct access will be returned. + """ + + entity: str = proto.Field( + proto.STRING, + number=1, + ) + dimensions: MutableSequence[access_report.AccessDimension] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=access_report.AccessDimension, + ) + metrics: MutableSequence[access_report.AccessMetric] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=access_report.AccessMetric, + ) + date_ranges: MutableSequence[access_report.AccessDateRange] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=access_report.AccessDateRange, + ) + dimension_filter: access_report.AccessFilterExpression = proto.Field( + proto.MESSAGE, + number=5, + message=access_report.AccessFilterExpression, + ) + metric_filter: access_report.AccessFilterExpression = proto.Field( + proto.MESSAGE, + number=6, + message=access_report.AccessFilterExpression, + ) + offset: int = proto.Field( + proto.INT64, + number=7, + ) + limit: int = proto.Field( + proto.INT64, + number=8, + ) + time_zone: str = proto.Field( + proto.STRING, + number=9, + ) + order_bys: MutableSequence[access_report.AccessOrderBy] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=access_report.AccessOrderBy, + ) + return_entity_quota: bool = proto.Field( + proto.BOOL, + number=11, + ) + include_all_users: bool = proto.Field( + proto.BOOL, + number=12, + ) + expand_groups: bool = proto.Field( + proto.BOOL, + number=13, + ) + + +class RunAccessReportResponse(proto.Message): + r"""The customized Data Access Record Report response. + + Attributes: + dimension_headers (MutableSequence[google.analytics.admin_v1beta.types.AccessDimensionHeader]): + The header for a column in the report that + corresponds to a specific dimension. The number + of DimensionHeaders and ordering of + DimensionHeaders matches the dimensions present + in rows. + metric_headers (MutableSequence[google.analytics.admin_v1beta.types.AccessMetricHeader]): + The header for a column in the report that + corresponds to a specific metric. The number of + MetricHeaders and ordering of MetricHeaders + matches the metrics present in rows. + rows (MutableSequence[google.analytics.admin_v1beta.types.AccessRow]): + Rows of dimension value combinations and + metric values in the report. + row_count (int): + The total number of rows in the query result. ``rowCount`` + is independent of the number of rows returned in the + response, the ``limit`` request parameter, and the + ``offset`` request parameter. For example if a query returns + 175 rows and includes ``limit`` of 50 in the API request, + the response will contain ``rowCount`` of 175 but only 50 + rows. + + To learn more about this pagination parameter, see + `Pagination `__. + quota (google.analytics.admin_v1beta.types.AccessQuota): + The quota state for this Analytics property + including this request. This field doesn't work + with account-level requests. + """ + + dimension_headers: MutableSequence[access_report.AccessDimensionHeader] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=access_report.AccessDimensionHeader, + ) + metric_headers: MutableSequence[access_report.AccessMetricHeader] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=access_report.AccessMetricHeader, + ) + rows: MutableSequence[access_report.AccessRow] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=access_report.AccessRow, + ) + row_count: int = proto.Field( + proto.INT32, + number=4, + ) + quota: access_report.AccessQuota = proto.Field( + proto.MESSAGE, + number=5, + message=access_report.AccessQuota, + ) + + +class GetAccountRequest(proto.Message): + r"""Request message for GetAccount RPC. + + Attributes: + name (str): + Required. The name of the account to lookup. + Format: accounts/{account} + Example: "accounts/100". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAccountsRequest(proto.Message): + r"""Request message for ListAccounts RPC. + + Attributes: + page_size (int): + The maximum number of resources to return. + The service may return fewer than this value, + even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListAccounts`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListAccounts`` must match the call that provided the page + token. + show_deleted (bool): + Whether to include soft-deleted (ie: + "trashed") Accounts in the results. Accounts can + be inspected to determine whether they are + deleted or not. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class ListAccountsResponse(proto.Message): + r"""Request message for ListAccounts RPC. + + Attributes: + accounts (MutableSequence[google.analytics.admin_v1beta.types.Account]): + Results that were accessible to the caller. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + accounts: MutableSequence[resources.Account] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Account, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteAccountRequest(proto.Message): + r"""Request message for DeleteAccount RPC. + + Attributes: + name (str): + Required. The name of the Account to + soft-delete. Format: accounts/{account} + Example: "accounts/100". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAccountRequest(proto.Message): + r"""Request message for UpdateAccount RPC. + + Attributes: + account (google.analytics.admin_v1beta.types.Account): + Required. The account to update. The account's ``name`` + field is used to identify the account. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (for example, "field_to_update"). Omitted + fields will not be updated. To replace the entire entity, + use one path with the string "*" to match all fields. + """ + + account: resources.Account = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Account, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ProvisionAccountTicketRequest(proto.Message): + r"""Request message for ProvisionAccountTicket RPC. + + Attributes: + account (google.analytics.admin_v1beta.types.Account): + The account to create. + redirect_uri (str): + Redirect URI where the user will be sent + after accepting Terms of Service. Must be + configured in Cloud Console as a Redirect URI. + """ + + account: resources.Account = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Account, + ) + redirect_uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ProvisionAccountTicketResponse(proto.Message): + r"""Response message for ProvisionAccountTicket RPC. + + Attributes: + account_ticket_id (str): + The param to be passed in the ToS link. + """ + + account_ticket_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetPropertyRequest(proto.Message): + r"""Request message for GetProperty RPC. + + Attributes: + name (str): + Required. The name of the property to lookup. Format: + properties/{property_id} Example: "properties/1000". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListPropertiesRequest(proto.Message): + r"""Request message for ListProperties RPC. + + Attributes: + filter (str): + Required. An expression for filtering the results of the + request. Fields eligible for filtering are: + ``parent:``\ (The resource name of the parent + account/property) or ``ancestor:``\ (The resource name of + the parent account) or ``firebase_project:``\ (The id or + number of the linked firebase project). Some examples of + filters: + + :: + + | Filter | Description | + |-----------------------------|-------------------------------------------| + | parent:accounts/123 | The account with account id: 123. | + | parent:properties/123 | The property with property id: 123. | + | ancestor:accounts/123 | The account with account id: 123. | + | firebase_project:project-id | The firebase project with id: project-id. | + | firebase_project:123 | The firebase project with number: 123. | + page_size (int): + The maximum number of resources to return. + The service may return fewer than this value, + even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListProperties`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListProperties`` must match the call that provided the + page token. + show_deleted (bool): + Whether to include soft-deleted (ie: + "trashed") Properties in the results. Properties + can be inspected to determine whether they are + deleted or not. + """ + + filter: 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, + ) + show_deleted: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListPropertiesResponse(proto.Message): + r"""Response message for ListProperties RPC. + + Attributes: + properties (MutableSequence[google.analytics.admin_v1beta.types.Property]): + Results that matched the filter criteria and + were accessible to the caller. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + properties: MutableSequence[resources.Property] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Property, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdatePropertyRequest(proto.Message): + r"""Request message for UpdateProperty RPC. + + Attributes: + property (google.analytics.admin_v1beta.types.Property): + Required. The property to update. The property's ``name`` + field is used to identify the property to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + property: resources.Property = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Property, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CreatePropertyRequest(proto.Message): + r"""Request message for CreateProperty RPC. + + Attributes: + property (google.analytics.admin_v1beta.types.Property): + Required. The property to create. + Note: the supplied property must specify its + parent. + """ + + property: resources.Property = proto.Field( + proto.MESSAGE, + number=1, + message=resources.Property, + ) + + +class DeletePropertyRequest(proto.Message): + r"""Request message for DeleteProperty RPC. + + Attributes: + name (str): + Required. The name of the Property to soft-delete. Format: + properties/{property_id} Example: "properties/1000". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateFirebaseLinkRequest(proto.Message): + r"""Request message for CreateFirebaseLink RPC + + Attributes: + parent (str): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + firebase_link (google.analytics.admin_v1beta.types.FirebaseLink): + Required. The Firebase link to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + firebase_link: resources.FirebaseLink = proto.Field( + proto.MESSAGE, + number=2, + message=resources.FirebaseLink, + ) + + +class DeleteFirebaseLinkRequest(proto.Message): + r"""Request message for DeleteFirebaseLink RPC + + Attributes: + name (str): + Required. Format: + properties/{property_id}/firebaseLinks/{firebase_link_id} + + Example: ``properties/1234/firebaseLinks/5678`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFirebaseLinksRequest(proto.Message): + r"""Request message for ListFirebaseLinks RPC + + Attributes: + parent (str): + Required. Format: properties/{property_id} + + Example: ``properties/1234`` + page_size (int): + The maximum number of resources to return. + The service may return fewer than this value, + even if there are additional pages. If + unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListFirebaseLinks`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListFirebaseLinks`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListFirebaseLinksResponse(proto.Message): + r"""Response message for ListFirebaseLinks RPC + + Attributes: + firebase_links (MutableSequence[google.analytics.admin_v1beta.types.FirebaseLink]): + List of FirebaseLinks. This will have at most + one value. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. Currently, Google Analytics supports only one + FirebaseLink per property, so this will never be populated. + """ + + @property + def raw_page(self): + return self + + firebase_links: MutableSequence[resources.FirebaseLink] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.FirebaseLink, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateGoogleAdsLinkRequest(proto.Message): + r"""Request message for CreateGoogleAdsLink RPC + + Attributes: + parent (str): + Required. Example format: properties/1234 + google_ads_link (google.analytics.admin_v1beta.types.GoogleAdsLink): + Required. The GoogleAdsLink to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + google_ads_link: resources.GoogleAdsLink = proto.Field( + proto.MESSAGE, + number=2, + message=resources.GoogleAdsLink, + ) + + +class UpdateGoogleAdsLinkRequest(proto.Message): + r"""Request message for UpdateGoogleAdsLink RPC + + Attributes: + google_ads_link (google.analytics.admin_v1beta.types.GoogleAdsLink): + The GoogleAdsLink to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + google_ads_link: resources.GoogleAdsLink = proto.Field( + proto.MESSAGE, + number=1, + message=resources.GoogleAdsLink, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteGoogleAdsLinkRequest(proto.Message): + r"""Request message for DeleteGoogleAdsLink RPC. + + Attributes: + name (str): + Required. Example format: + properties/1234/googleAdsLinks/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListGoogleAdsLinksRequest(proto.Message): + r"""Request message for ListGoogleAdsLinks RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous + ``ListGoogleAdsLinks`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListGoogleAdsLinks`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListGoogleAdsLinksResponse(proto.Message): + r"""Response message for ListGoogleAdsLinks RPC. + + Attributes: + google_ads_links (MutableSequence[google.analytics.admin_v1beta.types.GoogleAdsLink]): + List of GoogleAdsLinks. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + google_ads_links: MutableSequence[resources.GoogleAdsLink] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.GoogleAdsLink, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetDataSharingSettingsRequest(proto.Message): + r"""Request message for GetDataSharingSettings RPC. + + Attributes: + name (str): + Required. The name of the settings to lookup. Format: + accounts/{account}/dataSharingSettings + + Example: ``accounts/1000/dataSharingSettings`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAccountSummariesRequest(proto.Message): + r"""Request message for ListAccountSummaries RPC. + + Attributes: + page_size (int): + The maximum number of AccountSummary + resources to return. The service may return + fewer than this value, even if there are + additional pages. If unspecified, at most 50 + resources will be returned. The maximum value is + 200; (higher values will be coerced to the + maximum) + page_token (str): + A page token, received from a previous + ``ListAccountSummaries`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListAccountSummaries`` must match the call + that provided the page token. + """ + + page_size: int = proto.Field( + proto.INT32, + number=1, + ) + page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListAccountSummariesResponse(proto.Message): + r"""Response message for ListAccountSummaries RPC. + + Attributes: + account_summaries (MutableSequence[google.analytics.admin_v1beta.types.AccountSummary]): + Account summaries of all accounts the caller + has access to. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + account_summaries: MutableSequence[resources.AccountSummary] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.AccountSummary, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AcknowledgeUserDataCollectionRequest(proto.Message): + r"""Request message for AcknowledgeUserDataCollection RPC. + + Attributes: + property (str): + Required. The property for which to + acknowledge user data collection. + acknowledgement (str): + Required. An acknowledgement that the caller + of this method understands the terms of user + data collection. + + This field must contain the exact value: + + "I acknowledge that I have the necessary privacy + disclosures and rights from my end users for the + collection and processing of their data, + including the association of such data with the + visitation information Google Analytics collects + from my site and/or app property.". + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + acknowledgement: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AcknowledgeUserDataCollectionResponse(proto.Message): + r"""Response message for AcknowledgeUserDataCollection RPC. + """ + + +class SearchChangeHistoryEventsRequest(proto.Message): + r"""Request message for SearchChangeHistoryEvents RPC. + + Attributes: + account (str): + Required. The account resource for which to return change + history resources. Format: accounts/{account} + + Example: ``accounts/100`` + property (str): + Optional. Resource name for a child property. If set, only + return changes made to this property or its child resources. + Format: properties/{propertyId} + + Example: ``properties/100`` + resource_type (MutableSequence[google.analytics.admin_v1beta.types.ChangeHistoryResourceType]): + Optional. If set, only return changes if they + are for a resource that matches at least one of + these types. + action (MutableSequence[google.analytics.admin_v1beta.types.ActionType]): + Optional. If set, only return changes that + match one or more of these types of actions. + actor_email (MutableSequence[str]): + Optional. If set, only return changes if they + are made by a user in this list. + earliest_change_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. If set, only return changes made + after this time (inclusive). + latest_change_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. If set, only return changes made + before this time (inclusive). + page_size (int): + Optional. The maximum number of + ChangeHistoryEvent items to return. The service + may return fewer than this value, even if there + are additional pages. If unspecified, at most 50 + items will be returned. The maximum value is 200 + (higher values will be coerced to the maximum). + page_token (str): + Optional. A page token, received from a previous + ``SearchChangeHistoryEvents`` call. Provide this to retrieve + the subsequent page. When paginating, all other parameters + provided to ``SearchChangeHistoryEvents`` must match the + call that provided the page token. + """ + + account: str = proto.Field( + proto.STRING, + number=1, + ) + property: str = proto.Field( + proto.STRING, + number=2, + ) + resource_type: MutableSequence[resources.ChangeHistoryResourceType] = proto.RepeatedField( + proto.ENUM, + number=3, + enum=resources.ChangeHistoryResourceType, + ) + action: MutableSequence[resources.ActionType] = proto.RepeatedField( + proto.ENUM, + number=4, + enum=resources.ActionType, + ) + actor_email: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + earliest_change_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + latest_change_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + page_size: int = proto.Field( + proto.INT32, + number=8, + ) + page_token: str = proto.Field( + proto.STRING, + number=9, + ) + + +class SearchChangeHistoryEventsResponse(proto.Message): + r"""Response message for SearchAccounts RPC. + + Attributes: + change_history_events (MutableSequence[google.analytics.admin_v1beta.types.ChangeHistoryEvent]): + Results that were accessible to the caller. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + change_history_events: MutableSequence[resources.ChangeHistoryEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.ChangeHistoryEvent, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetMeasurementProtocolSecretRequest(proto.Message): + r"""Request message for GetMeasurementProtocolSecret RPC. + + Attributes: + name (str): + Required. The name of the measurement + protocol secret to lookup. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateMeasurementProtocolSecretRequest(proto.Message): + r"""Request message for CreateMeasurementProtocolSecret RPC + + Attributes: + parent (str): + Required. The parent resource where this + secret will be created. Format: + properties/{property}/dataStreams/{dataStream} + measurement_protocol_secret (google.analytics.admin_v1beta.types.MeasurementProtocolSecret): + Required. The measurement protocol secret to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + measurement_protocol_secret: resources.MeasurementProtocolSecret = proto.Field( + proto.MESSAGE, + number=2, + message=resources.MeasurementProtocolSecret, + ) + + +class DeleteMeasurementProtocolSecretRequest(proto.Message): + r"""Request message for DeleteMeasurementProtocolSecret RPC + + Attributes: + name (str): + Required. The name of the + MeasurementProtocolSecret to delete. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateMeasurementProtocolSecretRequest(proto.Message): + r"""Request message for UpdateMeasurementProtocolSecret RPC + + Attributes: + measurement_protocol_secret (google.analytics.admin_v1beta.types.MeasurementProtocolSecret): + Required. The measurement protocol secret to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. + Omitted fields will not be updated. + """ + + measurement_protocol_secret: resources.MeasurementProtocolSecret = proto.Field( + proto.MESSAGE, + number=1, + message=resources.MeasurementProtocolSecret, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListMeasurementProtocolSecretsRequest(proto.Message): + r"""Request message for ListMeasurementProtocolSecret RPC + + Attributes: + parent (str): + Required. The resource name of the parent + stream. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets + page_size (int): + The maximum number of resources to return. + If unspecified, at most 10 resources will be + returned. The maximum value is 10. Higher values + will be coerced to the maximum. + page_token (str): + A page token, received from a previous + ``ListMeasurementProtocolSecrets`` call. Provide this to + retrieve the subsequent page. When paginating, all other + parameters provided to ``ListMeasurementProtocolSecrets`` + must match the call that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListMeasurementProtocolSecretsResponse(proto.Message): + r"""Response message for ListMeasurementProtocolSecret RPC + + Attributes: + measurement_protocol_secrets (MutableSequence[google.analytics.admin_v1beta.types.MeasurementProtocolSecret]): + A list of secrets for the parent stream + specified in the request. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + measurement_protocol_secrets: MutableSequence[resources.MeasurementProtocolSecret] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.MeasurementProtocolSecret, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateConversionEventRequest(proto.Message): + r"""Request message for CreateConversionEvent RPC + + Attributes: + conversion_event (google.analytics.admin_v1beta.types.ConversionEvent): + Required. The conversion event to create. + parent (str): + Required. The resource name of the parent + property where this conversion event will be + created. Format: properties/123 + """ + + conversion_event: resources.ConversionEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.ConversionEvent, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateConversionEventRequest(proto.Message): + r"""Request message for UpdateConversionEvent RPC + + Attributes: + conversion_event (google.analytics.admin_v1beta.types.ConversionEvent): + Required. The conversion event to update. The ``name`` field + is used to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + conversion_event: resources.ConversionEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.ConversionEvent, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetConversionEventRequest(proto.Message): + r"""Request message for GetConversionEvent RPC + + Attributes: + name (str): + Required. The resource name of the conversion event to + retrieve. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteConversionEventRequest(proto.Message): + r"""Request message for DeleteConversionEvent RPC + + Attributes: + name (str): + Required. The resource name of the conversion event to + delete. Format: + properties/{property}/conversionEvents/{conversion_event} + Example: "properties/123/conversionEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListConversionEventsRequest(proto.Message): + r"""Request message for ListConversionEvents RPC + + Attributes: + parent (str): + Required. The resource name of the parent + property. Example: 'properties/123' + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous + ``ListConversionEvents`` call. Provide this to retrieve the + subsequent page. When paginating, all other parameters + provided to ``ListConversionEvents`` must match the call + that provided the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListConversionEventsResponse(proto.Message): + r"""Response message for ListConversionEvents RPC. + + Attributes: + conversion_events (MutableSequence[google.analytics.admin_v1beta.types.ConversionEvent]): + The requested conversion events + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + conversion_events: MutableSequence[resources.ConversionEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.ConversionEvent, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateKeyEventRequest(proto.Message): + r"""Request message for CreateKeyEvent RPC + + Attributes: + key_event (google.analytics.admin_v1beta.types.KeyEvent): + Required. The Key Event to create. + parent (str): + Required. The resource name of the parent + property where this Key Event will be created. + Format: properties/123 + """ + + key_event: resources.KeyEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.KeyEvent, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateKeyEventRequest(proto.Message): + r"""Request message for UpdateKeyEvent RPC + + Attributes: + key_event (google.analytics.admin_v1beta.types.KeyEvent): + Required. The Key Event to update. The ``name`` field is + used to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + key_event: resources.KeyEvent = proto.Field( + proto.MESSAGE, + number=1, + message=resources.KeyEvent, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetKeyEventRequest(proto.Message): + r"""Request message for GetKeyEvent RPC + + Attributes: + name (str): + Required. The resource name of the Key Event to retrieve. + Format: properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteKeyEventRequest(proto.Message): + r"""Request message for DeleteKeyEvent RPC + + Attributes: + name (str): + Required. The resource name of the Key Event to delete. + Format: properties/{property}/keyEvents/{key_event} Example: + "properties/123/keyEvents/456". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListKeyEventsRequest(proto.Message): + r"""Request message for ListKeyEvents RPC + + Attributes: + parent (str): + Required. The resource name of the parent + property. Example: 'properties/123' + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200; (higher + values will be coerced to the maximum) + page_token (str): + A page token, received from a previous ``ListKeyEvents`` + call. Provide this to retrieve the subsequent page. When + paginating, all other parameters provided to + ``ListKeyEvents`` must match the call that provided the page + token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListKeyEventsResponse(proto.Message): + r"""Response message for ListKeyEvents RPC. + + Attributes: + key_events (MutableSequence[google.analytics.admin_v1beta.types.KeyEvent]): + The requested Key Events + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + key_events: MutableSequence[resources.KeyEvent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.KeyEvent, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateCustomDimensionRequest(proto.Message): + r"""Request message for CreateCustomDimension RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + custom_dimension (google.analytics.admin_v1beta.types.CustomDimension): + Required. The CustomDimension to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + custom_dimension: resources.CustomDimension = proto.Field( + proto.MESSAGE, + number=2, + message=resources.CustomDimension, + ) + + +class UpdateCustomDimensionRequest(proto.Message): + r"""Request message for UpdateCustomDimension RPC. + + Attributes: + custom_dimension (google.analytics.admin_v1beta.types.CustomDimension): + The CustomDimension to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + custom_dimension: resources.CustomDimension = proto.Field( + proto.MESSAGE, + number=1, + message=resources.CustomDimension, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListCustomDimensionsRequest(proto.Message): + r"""Request message for ListCustomDimensions RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous + ``ListCustomDimensions`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListCustomDimensions`` must match the call that provided + the page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCustomDimensionsResponse(proto.Message): + r"""Response message for ListCustomDimensions RPC. + + Attributes: + custom_dimensions (MutableSequence[google.analytics.admin_v1beta.types.CustomDimension]): + List of CustomDimensions. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + custom_dimensions: MutableSequence[resources.CustomDimension] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CustomDimension, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ArchiveCustomDimensionRequest(proto.Message): + r"""Request message for ArchiveCustomDimension RPC. + + Attributes: + name (str): + Required. The name of the CustomDimension to + archive. Example format: + properties/1234/customDimensions/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetCustomDimensionRequest(proto.Message): + r"""Request message for GetCustomDimension RPC. + + Attributes: + name (str): + Required. The name of the CustomDimension to + get. Example format: + properties/1234/customDimensions/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateCustomMetricRequest(proto.Message): + r"""Request message for CreateCustomMetric RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + custom_metric (google.analytics.admin_v1beta.types.CustomMetric): + Required. The CustomMetric to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + custom_metric: resources.CustomMetric = proto.Field( + proto.MESSAGE, + number=2, + message=resources.CustomMetric, + ) + + +class UpdateCustomMetricRequest(proto.Message): + r"""Request message for UpdateCustomMetric RPC. + + Attributes: + custom_metric (google.analytics.admin_v1beta.types.CustomMetric): + The CustomMetric to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + custom_metric: resources.CustomMetric = proto.Field( + proto.MESSAGE, + number=1, + message=resources.CustomMetric, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListCustomMetricsRequest(proto.Message): + r"""Request message for ListCustomMetrics RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous ``ListCustomMetrics`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListCustomMetrics`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListCustomMetricsResponse(proto.Message): + r"""Response message for ListCustomMetrics RPC. + + Attributes: + custom_metrics (MutableSequence[google.analytics.admin_v1beta.types.CustomMetric]): + List of CustomMetrics. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + custom_metrics: MutableSequence[resources.CustomMetric] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CustomMetric, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ArchiveCustomMetricRequest(proto.Message): + r"""Request message for ArchiveCustomMetric RPC. + + Attributes: + name (str): + Required. The name of the CustomMetric to + archive. Example format: + properties/1234/customMetrics/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetCustomMetricRequest(proto.Message): + r"""Request message for GetCustomMetric RPC. + + Attributes: + name (str): + Required. The name of the CustomMetric to + get. Example format: + properties/1234/customMetrics/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetDataRetentionSettingsRequest(proto.Message): + r"""Request message for GetDataRetentionSettings RPC. + + Attributes: + name (str): + Required. The name of the settings to lookup. + Format: + + properties/{property}/dataRetentionSettings + Example: "properties/1000/dataRetentionSettings". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDataRetentionSettingsRequest(proto.Message): + r"""Request message for UpdateDataRetentionSettings RPC. + + Attributes: + data_retention_settings (google.analytics.admin_v1beta.types.DataRetentionSettings): + Required. The settings to update. The ``name`` field is used + to identify the settings to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Field names must + be in snake case (e.g., "field_to_update"). Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + data_retention_settings: resources.DataRetentionSettings = proto.Field( + proto.MESSAGE, + number=1, + message=resources.DataRetentionSettings, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class CreateDataStreamRequest(proto.Message): + r"""Request message for CreateDataStream RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + data_stream (google.analytics.admin_v1beta.types.DataStream): + Required. The DataStream to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + data_stream: resources.DataStream = proto.Field( + proto.MESSAGE, + number=2, + message=resources.DataStream, + ) + + +class DeleteDataStreamRequest(proto.Message): + r"""Request message for DeleteDataStream RPC. + + Attributes: + name (str): + Required. The name of the DataStream to + delete. Example format: + properties/1234/dataStreams/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateDataStreamRequest(proto.Message): + r"""Request message for UpdateDataStream RPC. + + Attributes: + data_stream (google.analytics.admin_v1beta.types.DataStream): + The DataStream to update + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to be updated. Omitted fields + will not be updated. To replace the entire entity, use one + path with the string "*" to match all fields. + """ + + data_stream: resources.DataStream = proto.Field( + proto.MESSAGE, + number=1, + message=resources.DataStream, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListDataStreamsRequest(proto.Message): + r"""Request message for ListDataStreams RPC. + + Attributes: + parent (str): + Required. Example format: properties/1234 + page_size (int): + The maximum number of resources to return. + If unspecified, at most 50 resources will be + returned. The maximum value is 200 (higher + values will be coerced to the maximum). + page_token (str): + A page token, received from a previous ``ListDataStreams`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListDataStreams`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDataStreamsResponse(proto.Message): + r"""Response message for ListDataStreams RPC. + + Attributes: + data_streams (MutableSequence[google.analytics.admin_v1beta.types.DataStream]): + List of DataStreams. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + data_streams: MutableSequence[resources.DataStream] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.DataStream, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetDataStreamRequest(proto.Message): + r"""Request message for GetDataStream RPC. + + Attributes: + name (str): + Required. The name of the DataStream to get. + Example format: properties/1234/dataStreams/5678 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/resources.py b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/resources.py new file mode 100644 index 000000000000..d7a5c989e139 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/google/analytics/admin_v1beta/types/resources.py @@ -0,0 +1,1654 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.analytics.admin.v1beta', + manifest={ + 'IndustryCategory', + 'ServiceLevel', + 'ActorType', + 'ActionType', + 'ChangeHistoryResourceType', + 'PropertyType', + 'Account', + 'Property', + 'DataStream', + 'FirebaseLink', + 'GoogleAdsLink', + 'DataSharingSettings', + 'AccountSummary', + 'PropertySummary', + 'MeasurementProtocolSecret', + 'ChangeHistoryEvent', + 'ChangeHistoryChange', + 'ConversionEvent', + 'KeyEvent', + 'CustomDimension', + 'CustomMetric', + 'DataRetentionSettings', + }, +) + + +class IndustryCategory(proto.Enum): + r"""The category selected for this property, used for industry + benchmarking. + + Values: + INDUSTRY_CATEGORY_UNSPECIFIED (0): + Industry category unspecified + AUTOMOTIVE (1): + Automotive + BUSINESS_AND_INDUSTRIAL_MARKETS (2): + Business and industrial markets + FINANCE (3): + Finance + HEALTHCARE (4): + Healthcare + TECHNOLOGY (5): + Technology + TRAVEL (6): + Travel + OTHER (7): + Other + ARTS_AND_ENTERTAINMENT (8): + Arts and entertainment + BEAUTY_AND_FITNESS (9): + Beauty and fitness + BOOKS_AND_LITERATURE (10): + Books and literature + FOOD_AND_DRINK (11): + Food and drink + GAMES (12): + Games + HOBBIES_AND_LEISURE (13): + Hobbies and leisure + HOME_AND_GARDEN (14): + Home and garden + INTERNET_AND_TELECOM (15): + Internet and telecom + LAW_AND_GOVERNMENT (16): + Law and government + NEWS (17): + News + ONLINE_COMMUNITIES (18): + Online communities + PEOPLE_AND_SOCIETY (19): + People and society + PETS_AND_ANIMALS (20): + Pets and animals + REAL_ESTATE (21): + Real estate + REFERENCE (22): + Reference + SCIENCE (23): + Science + SPORTS (24): + Sports + JOBS_AND_EDUCATION (25): + Jobs and education + SHOPPING (26): + Shopping + """ + INDUSTRY_CATEGORY_UNSPECIFIED = 0 + AUTOMOTIVE = 1 + BUSINESS_AND_INDUSTRIAL_MARKETS = 2 + FINANCE = 3 + HEALTHCARE = 4 + TECHNOLOGY = 5 + TRAVEL = 6 + OTHER = 7 + ARTS_AND_ENTERTAINMENT = 8 + BEAUTY_AND_FITNESS = 9 + BOOKS_AND_LITERATURE = 10 + FOOD_AND_DRINK = 11 + GAMES = 12 + HOBBIES_AND_LEISURE = 13 + HOME_AND_GARDEN = 14 + INTERNET_AND_TELECOM = 15 + LAW_AND_GOVERNMENT = 16 + NEWS = 17 + ONLINE_COMMUNITIES = 18 + PEOPLE_AND_SOCIETY = 19 + PETS_AND_ANIMALS = 20 + REAL_ESTATE = 21 + REFERENCE = 22 + SCIENCE = 23 + SPORTS = 24 + JOBS_AND_EDUCATION = 25 + SHOPPING = 26 + + +class ServiceLevel(proto.Enum): + r"""Various levels of service for Google Analytics. + + Values: + SERVICE_LEVEL_UNSPECIFIED (0): + Service level not specified or invalid. + GOOGLE_ANALYTICS_STANDARD (1): + The standard version of Google Analytics. + GOOGLE_ANALYTICS_360 (2): + The paid, premium version of Google + Analytics. + """ + SERVICE_LEVEL_UNSPECIFIED = 0 + GOOGLE_ANALYTICS_STANDARD = 1 + GOOGLE_ANALYTICS_360 = 2 + + +class ActorType(proto.Enum): + r"""Different kinds of actors that can make changes to Google + Analytics resources. + + Values: + ACTOR_TYPE_UNSPECIFIED (0): + Unknown or unspecified actor type. + USER (1): + Changes made by the user specified in actor_email. + SYSTEM (2): + Changes made by the Google Analytics system. + SUPPORT (3): + Changes made by Google Analytics support team + staff. + """ + ACTOR_TYPE_UNSPECIFIED = 0 + USER = 1 + SYSTEM = 2 + SUPPORT = 3 + + +class ActionType(proto.Enum): + r"""Types of actions that may change a resource. + + Values: + ACTION_TYPE_UNSPECIFIED (0): + Action type unknown or not specified. + CREATED (1): + Resource was created in this change. + UPDATED (2): + Resource was updated in this change. + DELETED (3): + Resource was deleted in this change. + """ + ACTION_TYPE_UNSPECIFIED = 0 + CREATED = 1 + UPDATED = 2 + DELETED = 3 + + +class ChangeHistoryResourceType(proto.Enum): + r"""Types of resources whose changes may be returned from change + history. + + Values: + CHANGE_HISTORY_RESOURCE_TYPE_UNSPECIFIED (0): + Resource type unknown or not specified. + ACCOUNT (1): + Account resource + PROPERTY (2): + Property resource + FIREBASE_LINK (6): + FirebaseLink resource + GOOGLE_ADS_LINK (7): + GoogleAdsLink resource + GOOGLE_SIGNALS_SETTINGS (8): + GoogleSignalsSettings resource + CONVERSION_EVENT (9): + ConversionEvent resource + MEASUREMENT_PROTOCOL_SECRET (10): + MeasurementProtocolSecret resource + DATA_RETENTION_SETTINGS (13): + DataRetentionSettings resource + DISPLAY_VIDEO_360_ADVERTISER_LINK (14): + DisplayVideo360AdvertiserLink resource + DISPLAY_VIDEO_360_ADVERTISER_LINK_PROPOSAL (15): + DisplayVideo360AdvertiserLinkProposal + resource + DATA_STREAM (18): + DataStream resource + ATTRIBUTION_SETTINGS (20): + AttributionSettings resource + """ + CHANGE_HISTORY_RESOURCE_TYPE_UNSPECIFIED = 0 + ACCOUNT = 1 + PROPERTY = 2 + FIREBASE_LINK = 6 + GOOGLE_ADS_LINK = 7 + GOOGLE_SIGNALS_SETTINGS = 8 + CONVERSION_EVENT = 9 + MEASUREMENT_PROTOCOL_SECRET = 10 + DATA_RETENTION_SETTINGS = 13 + DISPLAY_VIDEO_360_ADVERTISER_LINK = 14 + DISPLAY_VIDEO_360_ADVERTISER_LINK_PROPOSAL = 15 + DATA_STREAM = 18 + ATTRIBUTION_SETTINGS = 20 + + +class PropertyType(proto.Enum): + r"""Types of Property resources. + + Values: + PROPERTY_TYPE_UNSPECIFIED (0): + Unknown or unspecified property type + PROPERTY_TYPE_ORDINARY (1): + Ordinary GA4 property + PROPERTY_TYPE_SUBPROPERTY (2): + GA4 subproperty + PROPERTY_TYPE_ROLLUP (3): + GA4 rollup property + """ + PROPERTY_TYPE_UNSPECIFIED = 0 + PROPERTY_TYPE_ORDINARY = 1 + PROPERTY_TYPE_SUBPROPERTY = 2 + PROPERTY_TYPE_ROLLUP = 3 + + +class Account(proto.Message): + r"""A resource message representing a Google Analytics account. + + Attributes: + name (str): + Output only. Resource name of this account. + Format: accounts/{account} + Example: "accounts/100". + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this account was + originally created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when account payload fields + were last updated. + display_name (str): + Required. Human-readable display name for + this account. + region_code (str): + Country of business. Must be a Unicode CLDR + region code. + deleted (bool): + Output only. Indicates whether this Account + is soft-deleted or not. Deleted accounts are + excluded from List results unless specifically + requested. + gmp_organization (str): + Output only. The URI for a Google Marketing Platform + organization resource. Only set when this account is + connected to a GMP organization. Format: + marketingplatformadmin.googleapis.com/organizations/{org_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + region_code: str = proto.Field( + proto.STRING, + number=5, + ) + deleted: bool = proto.Field( + proto.BOOL, + number=6, + ) + gmp_organization: str = proto.Field( + proto.STRING, + number=7, + ) + + +class Property(proto.Message): + r"""A resource message representing a Google Analytics GA4 + property. + + Attributes: + name (str): + Output only. Resource name of this property. Format: + properties/{property_id} Example: "properties/1000". + property_type (google.analytics.admin_v1beta.types.PropertyType): + Immutable. The property type for this Property resource. + When creating a property, if the type is + "PROPERTY_TYPE_UNSPECIFIED", then "ORDINARY_PROPERTY" will + be implied. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the entity was + originally created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when entity payload fields + were last updated. + parent (str): + Immutable. Resource name of this property's + logical parent. + Note: The Property-Moving UI can be used to + change the parent. Format: accounts/{account}, + properties/{property} Example: "accounts/100", + "properties/101". + display_name (str): + Required. Human-readable display name for + this property. + The max allowed display name length is 100 + UTF-16 code units. + industry_category (google.analytics.admin_v1beta.types.IndustryCategory): + Industry associated with this property Example: AUTOMOTIVE, + FOOD_AND_DRINK + time_zone (str): + Required. Reporting Time Zone, used as the day boundary for + reports, regardless of where the data originates. If the + time zone honors DST, Analytics will automatically adjust + for the changes. + + NOTE: Changing the time zone only affects data going + forward, and is not applied retroactively. + + Format: https://www.iana.org/time-zones Example: + "America/Los_Angeles". + currency_code (str): + The currency type used in reports involving monetary values. + + Format: https://en.wikipedia.org/wiki/ISO_4217 Examples: + "USD", "EUR", "JPY". + service_level (google.analytics.admin_v1beta.types.ServiceLevel): + Output only. The Google Analytics service + level that applies to this property. + delete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. If set, the time at which this + property was trashed. If not set, then this + property is not currently in the trash can. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. If set, the time at which this + trashed property will be permanently deleted. If + not set, then this property is not currently in + the trash can and is not slated to be deleted. + account (str): + Immutable. The resource name of the parent account Format: + accounts/{account_id} Example: "accounts/123". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + property_type: 'PropertyType' = proto.Field( + proto.ENUM, + number=14, + enum='PropertyType', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + industry_category: 'IndustryCategory' = proto.Field( + proto.ENUM, + number=6, + enum='IndustryCategory', + ) + time_zone: str = proto.Field( + proto.STRING, + number=7, + ) + currency_code: str = proto.Field( + proto.STRING, + number=8, + ) + service_level: 'ServiceLevel' = proto.Field( + proto.ENUM, + number=10, + enum='ServiceLevel', + ) + delete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + account: str = proto.Field( + proto.STRING, + number=13, + ) + + +class DataStream(proto.Message): + r"""A resource message representing a data stream. + + 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: + web_stream_data (google.analytics.admin_v1beta.types.DataStream.WebStreamData): + Data specific to web streams. Must be populated if type is + WEB_DATA_STREAM. + + This field is a member of `oneof`_ ``stream_data``. + android_app_stream_data (google.analytics.admin_v1beta.types.DataStream.AndroidAppStreamData): + Data specific to Android app streams. Must be populated if + type is ANDROID_APP_DATA_STREAM. + + This field is a member of `oneof`_ ``stream_data``. + ios_app_stream_data (google.analytics.admin_v1beta.types.DataStream.IosAppStreamData): + Data specific to iOS app streams. Must be populated if type + is IOS_APP_DATA_STREAM. + + This field is a member of `oneof`_ ``stream_data``. + name (str): + Output only. Resource name of this Data Stream. Format: + properties/{property_id}/dataStreams/{stream_id} Example: + "properties/1000/dataStreams/2000". + type_ (google.analytics.admin_v1beta.types.DataStream.DataStreamType): + Required. Immutable. The type of this + DataStream resource. + display_name (str): + Human-readable display name for the Data + Stream. + Required for web data streams. + + The max allowed display name length is 255 + UTF-16 code units. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this stream was + originally created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when stream payload fields + were last updated. + """ + class DataStreamType(proto.Enum): + r"""The type of the data stream. + + Values: + DATA_STREAM_TYPE_UNSPECIFIED (0): + Type unknown or not specified. + WEB_DATA_STREAM (1): + Web data stream. + ANDROID_APP_DATA_STREAM (2): + Android app data stream. + IOS_APP_DATA_STREAM (3): + iOS app data stream. + """ + DATA_STREAM_TYPE_UNSPECIFIED = 0 + WEB_DATA_STREAM = 1 + ANDROID_APP_DATA_STREAM = 2 + IOS_APP_DATA_STREAM = 3 + + class WebStreamData(proto.Message): + r"""Data specific to web streams. + + Attributes: + measurement_id (str): + Output only. Analytics Measurement ID. + + Example: "G-1A2BCD345E". + firebase_app_id (str): + Output only. ID of the corresponding web app + in Firebase, if any. This ID can change if the + web app is deleted and recreated. + default_uri (str): + Domain name of the web app being measured, or + empty. Example: "http://www.google.com", + "https://www.google.com". + """ + + measurement_id: str = proto.Field( + proto.STRING, + number=1, + ) + firebase_app_id: str = proto.Field( + proto.STRING, + number=2, + ) + default_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + class AndroidAppStreamData(proto.Message): + r"""Data specific to Android app streams. + + Attributes: + firebase_app_id (str): + Output only. ID of the corresponding Android + app in Firebase, if any. This ID can change if + the Android app is deleted and recreated. + package_name (str): + Immutable. The package name for the app being + measured. Example: "com.example.myandroidapp". + """ + + firebase_app_id: str = proto.Field( + proto.STRING, + number=1, + ) + package_name: str = proto.Field( + proto.STRING, + number=2, + ) + + class IosAppStreamData(proto.Message): + r"""Data specific to iOS app streams. + + Attributes: + firebase_app_id (str): + Output only. ID of the corresponding iOS app + in Firebase, if any. This ID can change if the + iOS app is deleted and recreated. + bundle_id (str): + Required. Immutable. The Apple App Store + Bundle ID for the app Example: + "com.example.myiosapp". + """ + + firebase_app_id: str = proto.Field( + proto.STRING, + number=1, + ) + bundle_id: str = proto.Field( + proto.STRING, + number=2, + ) + + web_stream_data: WebStreamData = proto.Field( + proto.MESSAGE, + number=6, + oneof='stream_data', + message=WebStreamData, + ) + android_app_stream_data: AndroidAppStreamData = proto.Field( + proto.MESSAGE, + number=7, + oneof='stream_data', + message=AndroidAppStreamData, + ) + ios_app_stream_data: IosAppStreamData = proto.Field( + proto.MESSAGE, + number=8, + oneof='stream_data', + message=IosAppStreamData, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: DataStreamType = proto.Field( + proto.ENUM, + number=2, + enum=DataStreamType, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class FirebaseLink(proto.Message): + r"""A link between a GA4 property and a Firebase project. + + Attributes: + name (str): + Output only. Example format: + properties/1234/firebaseLinks/5678 + project (str): + Immutable. Firebase project resource name. When creating a + FirebaseLink, you may provide this resource name using + either a project number or project ID. Once this resource + has been created, returned FirebaseLinks will always have a + project_name that contains a project number. + + Format: 'projects/{project number}' Example: 'projects/1234' + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this FirebaseLink was + originally created. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + project: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class GoogleAdsLink(proto.Message): + r"""A link between a GA4 property and a Google Ads account. + + Attributes: + name (str): + Output only. Format: + + properties/{propertyId}/googleAdsLinks/{googleAdsLinkId} + + Note: googleAdsLinkId is not the Google Ads + customer ID. + customer_id (str): + Immutable. Google Ads customer ID. + can_manage_clients (bool): + Output only. If true, this link is for a + Google Ads manager account. + ads_personalization_enabled (google.protobuf.wrappers_pb2.BoolValue): + Enable personalized advertising features with + this integration. Automatically publish my + Google Analytics audience lists and Google + Analytics remarketing events/parameters to the + linked Google Ads account. If this field is not + set on create/update, it will be defaulted to + true. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this link was + originally created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this link was last + updated. + creator_email_address (str): + Output only. Email address of the user that + created the link. An empty string will be + returned if the email address can't be + retrieved. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + customer_id: str = proto.Field( + proto.STRING, + number=3, + ) + can_manage_clients: bool = proto.Field( + proto.BOOL, + number=4, + ) + ads_personalization_enabled: wrappers_pb2.BoolValue = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.BoolValue, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + creator_email_address: str = proto.Field( + proto.STRING, + number=9, + ) + + +class DataSharingSettings(proto.Message): + r"""A resource message representing data sharing settings of a + Google Analytics account. + + Attributes: + name (str): + Output only. Resource name. + Format: accounts/{account}/dataSharingSettings + Example: "accounts/1000/dataSharingSettings". + sharing_with_google_support_enabled (bool): + Allows Google support to access the data in + order to help troubleshoot issues. + sharing_with_google_assigned_sales_enabled (bool): + Allows Google sales teams that are assigned + to the customer to access the data in order to + suggest configuration changes to improve + results. Sales team restrictions still apply + when enabled. + sharing_with_google_any_sales_enabled (bool): + Allows any of Google sales to access the data + in order to suggest configuration changes to + improve results. + sharing_with_google_products_enabled (bool): + Allows Google to use the data to improve + other Google products or services. + sharing_with_others_enabled (bool): + Allows Google to share the data anonymously + in aggregate form with others. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + sharing_with_google_support_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + sharing_with_google_assigned_sales_enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + sharing_with_google_any_sales_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + sharing_with_google_products_enabled: bool = proto.Field( + proto.BOOL, + number=5, + ) + sharing_with_others_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class AccountSummary(proto.Message): + r"""A virtual resource representing an overview of an account and + all its child GA4 properties. + + Attributes: + name (str): + Resource name for this account summary. Format: + accountSummaries/{account_id} Example: + "accountSummaries/1000". + account (str): + Resource name of account referred to by this account summary + Format: accounts/{account_id} Example: "accounts/1000". + display_name (str): + Display name for the account referred to in + this account summary. + property_summaries (MutableSequence[google.analytics.admin_v1beta.types.PropertySummary]): + List of summaries for child accounts of this + account. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + account: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + property_summaries: MutableSequence['PropertySummary'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='PropertySummary', + ) + + +class PropertySummary(proto.Message): + r"""A virtual resource representing metadata for a GA4 property. + + Attributes: + property (str): + Resource name of property referred to by this property + summary Format: properties/{property_id} Example: + "properties/1000". + display_name (str): + Display name for the property referred to in + this property summary. + property_type (google.analytics.admin_v1beta.types.PropertyType): + The property's property type. + parent (str): + Resource name of this property's logical + parent. + Note: The Property-Moving UI can be used to + change the parent. Format: accounts/{account}, + properties/{property} Example: "accounts/100", + "properties/200". + """ + + property: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + property_type: 'PropertyType' = proto.Field( + proto.ENUM, + number=3, + enum='PropertyType', + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + + +class MeasurementProtocolSecret(proto.Message): + r"""A secret value used for sending hits to Measurement Protocol. + + Attributes: + name (str): + Output only. Resource name of this secret. + This secret may be a child of any type of + stream. Format: + + properties/{property}/dataStreams/{dataStream}/measurementProtocolSecrets/{measurementProtocolSecret} + display_name (str): + Required. Human-readable display name for + this secret. + secret_value (str): + Output only. The measurement protocol secret value. Pass + this value to the api_secret field of the Measurement + Protocol API when sending hits to this secret's parent + property. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + secret_value: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ChangeHistoryEvent(proto.Message): + r"""A set of changes within a Google Analytics account or its + child properties that resulted from the same cause. Common + causes would be updates made in the Google Analytics UI, changes + from customer support, or automatic Google Analytics system + changes. + + Attributes: + id (str): + ID of this change history event. This ID is + unique across Google Analytics. + change_time (google.protobuf.timestamp_pb2.Timestamp): + Time when change was made. + actor_type (google.analytics.admin_v1beta.types.ActorType): + The type of actor that made this change. + user_actor_email (str): + Email address of the Google account that made + the change. This will be a valid email address + if the actor field is set to USER, and empty + otherwise. Google accounts that have been + deleted will cause an error. + changes_filtered (bool): + If true, then the list of changes returned + was filtered, and does not represent all changes + that occurred in this event. + changes (MutableSequence[google.analytics.admin_v1beta.types.ChangeHistoryChange]): + A list of changes made in this change history + event that fit the filters specified in + SearchChangeHistoryEventsRequest. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + change_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + actor_type: 'ActorType' = proto.Field( + proto.ENUM, + number=3, + enum='ActorType', + ) + user_actor_email: str = proto.Field( + proto.STRING, + number=4, + ) + changes_filtered: bool = proto.Field( + proto.BOOL, + number=5, + ) + changes: MutableSequence['ChangeHistoryChange'] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message='ChangeHistoryChange', + ) + + +class ChangeHistoryChange(proto.Message): + r"""A description of a change to a single Google Analytics + resource. + + Attributes: + resource (str): + Resource name of the resource whose changes + are described by this entry. + action (google.analytics.admin_v1beta.types.ActionType): + The type of action that changed this + resource. + resource_before_change (google.analytics.admin_v1beta.types.ChangeHistoryChange.ChangeHistoryResource): + Resource contents from before the change was + made. If this resource was created in this + change, this field will be missing. + resource_after_change (google.analytics.admin_v1beta.types.ChangeHistoryChange.ChangeHistoryResource): + Resource contents from after the change was + made. If this resource was deleted in this + change, this field will be missing. + """ + + class ChangeHistoryResource(proto.Message): + r"""A snapshot of a resource as before or after the result of a + change in change history. + + 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: + account (google.analytics.admin_v1beta.types.Account): + A snapshot of an Account resource in change + history. + + This field is a member of `oneof`_ ``resource``. + property (google.analytics.admin_v1beta.types.Property): + A snapshot of a Property resource in change + history. + + This field is a member of `oneof`_ ``resource``. + firebase_link (google.analytics.admin_v1beta.types.FirebaseLink): + A snapshot of a FirebaseLink resource in + change history. + + This field is a member of `oneof`_ ``resource``. + google_ads_link (google.analytics.admin_v1beta.types.GoogleAdsLink): + A snapshot of a GoogleAdsLink resource in + change history. + + This field is a member of `oneof`_ ``resource``. + conversion_event (google.analytics.admin_v1beta.types.ConversionEvent): + A snapshot of a ConversionEvent resource in + change history. + + This field is a member of `oneof`_ ``resource``. + measurement_protocol_secret (google.analytics.admin_v1beta.types.MeasurementProtocolSecret): + A snapshot of a MeasurementProtocolSecret + resource in change history. + + This field is a member of `oneof`_ ``resource``. + data_retention_settings (google.analytics.admin_v1beta.types.DataRetentionSettings): + A snapshot of a data retention settings + resource in change history. + + This field is a member of `oneof`_ ``resource``. + data_stream (google.analytics.admin_v1beta.types.DataStream): + A snapshot of a DataStream resource in change + history. + + This field is a member of `oneof`_ ``resource``. + """ + + account: 'Account' = proto.Field( + proto.MESSAGE, + number=1, + oneof='resource', + message='Account', + ) + property: 'Property' = proto.Field( + proto.MESSAGE, + number=2, + oneof='resource', + message='Property', + ) + firebase_link: 'FirebaseLink' = proto.Field( + proto.MESSAGE, + number=6, + oneof='resource', + message='FirebaseLink', + ) + google_ads_link: 'GoogleAdsLink' = proto.Field( + proto.MESSAGE, + number=7, + oneof='resource', + message='GoogleAdsLink', + ) + conversion_event: 'ConversionEvent' = proto.Field( + proto.MESSAGE, + number=11, + oneof='resource', + message='ConversionEvent', + ) + measurement_protocol_secret: 'MeasurementProtocolSecret' = proto.Field( + proto.MESSAGE, + number=12, + oneof='resource', + message='MeasurementProtocolSecret', + ) + data_retention_settings: 'DataRetentionSettings' = proto.Field( + proto.MESSAGE, + number=15, + oneof='resource', + message='DataRetentionSettings', + ) + data_stream: 'DataStream' = proto.Field( + proto.MESSAGE, + number=18, + oneof='resource', + message='DataStream', + ) + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + action: 'ActionType' = proto.Field( + proto.ENUM, + number=2, + enum='ActionType', + ) + resource_before_change: ChangeHistoryResource = proto.Field( + proto.MESSAGE, + number=3, + message=ChangeHistoryResource, + ) + resource_after_change: ChangeHistoryResource = proto.Field( + proto.MESSAGE, + number=4, + message=ChangeHistoryResource, + ) + + +class ConversionEvent(proto.Message): + r"""A conversion event in a Google Analytics property. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Resource name of this conversion event. Format: + properties/{property}/conversionEvents/{conversion_event} + event_name (str): + Immutable. The event name for this conversion + event. Examples: 'click', 'purchase' + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this conversion event + was created in the property. + deletable (bool): + Output only. If set, this event can currently + be deleted with DeleteConversionEvent. + custom (bool): + Output only. If set to true, this conversion + event refers to a custom event. If set to + false, this conversion event refers to a default + event in GA. Default events typically have + special meaning in GA. Default events are + usually created for you by the GA system, but in + some cases can be created by property admins. + Custom events count towards the maximum number + of custom conversion events that may be created + per property. + counting_method (google.analytics.admin_v1beta.types.ConversionEvent.ConversionCountingMethod): + Optional. The method by which conversions will be counted + across multiple events within a session. If this value is + not provided, it will be set to ``ONCE_PER_EVENT``. + default_conversion_value (google.analytics.admin_v1beta.types.ConversionEvent.DefaultConversionValue): + Optional. Defines a default value/currency + for a conversion event. + + This field is a member of `oneof`_ ``_default_conversion_value``. + """ + class ConversionCountingMethod(proto.Enum): + r"""The method by which conversions will be counted across + multiple events within a session. + + Values: + CONVERSION_COUNTING_METHOD_UNSPECIFIED (0): + Counting method not specified. + ONCE_PER_EVENT (1): + Each Event instance is considered a + Conversion. + ONCE_PER_SESSION (2): + An Event instance is considered a Conversion + at most once per session per user. + """ + CONVERSION_COUNTING_METHOD_UNSPECIFIED = 0 + ONCE_PER_EVENT = 1 + ONCE_PER_SESSION = 2 + + class DefaultConversionValue(proto.Message): + r"""Defines a default value/currency for a conversion event. Both + value and currency must be provided. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (float): + This value will be used to populate the value for all + conversions of the specified event_name where the event + "value" parameter is unset. + + This field is a member of `oneof`_ ``_value``. + currency_code (str): + When a conversion event for this event_name has no set + currency, this currency will be applied as the default. Must + be in ISO 4217 currency code format. See + https://en.wikipedia.org/wiki/ISO_4217 for more information. + + This field is a member of `oneof`_ ``_currency_code``. + """ + + value: float = proto.Field( + proto.DOUBLE, + number=1, + optional=True, + ) + currency_code: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + event_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + deletable: bool = proto.Field( + proto.BOOL, + number=4, + ) + custom: bool = proto.Field( + proto.BOOL, + number=5, + ) + counting_method: ConversionCountingMethod = proto.Field( + proto.ENUM, + number=6, + enum=ConversionCountingMethod, + ) + default_conversion_value: DefaultConversionValue = proto.Field( + proto.MESSAGE, + number=7, + optional=True, + message=DefaultConversionValue, + ) + + +class KeyEvent(proto.Message): + r"""A key event in a Google Analytics property. + + Attributes: + name (str): + Output only. Resource name of this key event. Format: + properties/{property}/keyEvents/{key_event} + event_name (str): + Immutable. The event name for this key event. + Examples: 'click', 'purchase' + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when this key event was + created in the property. + deletable (bool): + Output only. If set to true, this event can + be deleted. + custom (bool): + Output only. If set to true, this key event + refers to a custom event. If set to false, this + key event refers to a default event in GA. + Default events typically have special meaning in + GA. Default events are usually created for you + by the GA system, but in some cases can be + created by property admins. Custom events count + towards the maximum number of custom key events + that may be created per property. + counting_method (google.analytics.admin_v1beta.types.KeyEvent.CountingMethod): + Required. The method by which Key Events will + be counted across multiple events within a + session. + default_value (google.analytics.admin_v1beta.types.KeyEvent.DefaultValue): + Optional. Defines a default value/currency + for a key event. + """ + class CountingMethod(proto.Enum): + r"""The method by which Key Events will be counted across + multiple events within a session. + + Values: + COUNTING_METHOD_UNSPECIFIED (0): + Counting method not specified. + ONCE_PER_EVENT (1): + Each Event instance is considered a Key + Event. + ONCE_PER_SESSION (2): + An Event instance is considered a Key Event + at most once per session per user. + """ + COUNTING_METHOD_UNSPECIFIED = 0 + ONCE_PER_EVENT = 1 + ONCE_PER_SESSION = 2 + + class DefaultValue(proto.Message): + r"""Defines a default value/currency for a key event. + + Attributes: + numeric_value (float): + Required. This will be used to populate the "value" + parameter for all occurrences of this Key Event (specified + by event_name) where that parameter is unset. + currency_code (str): + Required. When an occurrence of this Key Event (specified by + event_name) has no set currency this currency will be + applied as the default. Must be in ISO 4217 currency code + format. + + See https://en.wikipedia.org/wiki/ISO_4217 for more + information. + """ + + numeric_value: float = proto.Field( + proto.DOUBLE, + number=1, + ) + currency_code: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + event_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + deletable: bool = proto.Field( + proto.BOOL, + number=4, + ) + custom: bool = proto.Field( + proto.BOOL, + number=5, + ) + counting_method: CountingMethod = proto.Field( + proto.ENUM, + number=6, + enum=CountingMethod, + ) + default_value: DefaultValue = proto.Field( + proto.MESSAGE, + number=7, + message=DefaultValue, + ) + + +class CustomDimension(proto.Message): + r"""A definition for a CustomDimension. + + Attributes: + name (str): + Output only. Resource name for this + CustomDimension resource. Format: + properties/{property}/customDimensions/{customDimension} + parameter_name (str): + Required. Immutable. Tagging parameter name + for this custom dimension. + If this is a user-scoped dimension, then this is + the user property name. If this is an + event-scoped dimension, then this is the event + parameter name. + + If this is an item-scoped dimension, then this + is the parameter name found in the eCommerce + items array. + + May only contain alphanumeric and underscore + characters, starting with a letter. Max length + of 24 characters for user-scoped dimensions, 40 + characters for event-scoped dimensions. + display_name (str): + Required. Display name for this custom + dimension as shown in the Analytics UI. Max + length of 82 characters, alphanumeric plus space + and underscore starting with a letter. Legacy + system-generated display names may contain + square brackets, but updates to this field will + never permit square brackets. + description (str): + Optional. Description for this custom + dimension. Max length of 150 characters. + scope (google.analytics.admin_v1beta.types.CustomDimension.DimensionScope): + Required. Immutable. The scope of this + dimension. + disallow_ads_personalization (bool): + Optional. If set to true, sets this dimension + as NPA and excludes it from ads personalization. + + This is currently only supported by user-scoped + custom dimensions. + """ + class DimensionScope(proto.Enum): + r"""Valid values for the scope of this dimension. + + Values: + DIMENSION_SCOPE_UNSPECIFIED (0): + Scope unknown or not specified. + EVENT (1): + Dimension scoped to an event. + USER (2): + Dimension scoped to a user. + ITEM (3): + Dimension scoped to eCommerce items + """ + DIMENSION_SCOPE_UNSPECIFIED = 0 + EVENT = 1 + USER = 2 + ITEM = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parameter_name: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + scope: DimensionScope = proto.Field( + proto.ENUM, + number=5, + enum=DimensionScope, + ) + disallow_ads_personalization: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class CustomMetric(proto.Message): + r"""A definition for a custom metric. + + Attributes: + name (str): + Output only. Resource name for this + CustomMetric resource. Format: + properties/{property}/customMetrics/{customMetric} + parameter_name (str): + Required. Immutable. Tagging name for this + custom metric. + If this is an event-scoped metric, then this is + the event parameter name. + + May only contain alphanumeric and underscore + charactes, starting with a letter. Max length of + 40 characters for event-scoped metrics. + display_name (str): + Required. Display name for this custom metric + as shown in the Analytics UI. Max length of 82 + characters, alphanumeric plus space and + underscore starting with a letter. Legacy + system-generated display names may contain + square brackets, but updates to this field will + never permit square brackets. + description (str): + Optional. Description for this custom + dimension. Max length of 150 characters. + measurement_unit (google.analytics.admin_v1beta.types.CustomMetric.MeasurementUnit): + Required. The type for the custom metric's + value. + scope (google.analytics.admin_v1beta.types.CustomMetric.MetricScope): + Required. Immutable. The scope of this custom + metric. + restricted_metric_type (MutableSequence[google.analytics.admin_v1beta.types.CustomMetric.RestrictedMetricType]): + Optional. Types of restricted data that this + metric may contain. Required for metrics with + CURRENCY measurement unit. Must be empty for + metrics with a non-CURRENCY measurement unit. + """ + class MeasurementUnit(proto.Enum): + r"""Possible types of representing the custom metric's value. + + Currency representation may change in the future, requiring a + breaking API change. + + Values: + MEASUREMENT_UNIT_UNSPECIFIED (0): + MeasurementUnit unspecified or missing. + STANDARD (1): + This metric uses default units. + CURRENCY (2): + This metric measures a currency. + FEET (3): + This metric measures feet. + METERS (4): + This metric measures meters. + KILOMETERS (5): + This metric measures kilometers. + MILES (6): + This metric measures miles. + MILLISECONDS (7): + This metric measures milliseconds. + SECONDS (8): + This metric measures seconds. + MINUTES (9): + This metric measures minutes. + HOURS (10): + This metric measures hours. + """ + MEASUREMENT_UNIT_UNSPECIFIED = 0 + STANDARD = 1 + CURRENCY = 2 + FEET = 3 + METERS = 4 + KILOMETERS = 5 + MILES = 6 + MILLISECONDS = 7 + SECONDS = 8 + MINUTES = 9 + HOURS = 10 + + class MetricScope(proto.Enum): + r"""The scope of this metric. + + Values: + METRIC_SCOPE_UNSPECIFIED (0): + Scope unknown or not specified. + EVENT (1): + Metric scoped to an event. + """ + METRIC_SCOPE_UNSPECIFIED = 0 + EVENT = 1 + + class RestrictedMetricType(proto.Enum): + r"""Labels that mark the data in this custom metric as data that + should be restricted to specific users. + + Values: + RESTRICTED_METRIC_TYPE_UNSPECIFIED (0): + Type unknown or unspecified. + COST_DATA (1): + Metric reports cost data. + REVENUE_DATA (2): + Metric reports revenue data. + """ + RESTRICTED_METRIC_TYPE_UNSPECIFIED = 0 + COST_DATA = 1 + REVENUE_DATA = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parameter_name: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + measurement_unit: MeasurementUnit = proto.Field( + proto.ENUM, + number=5, + enum=MeasurementUnit, + ) + scope: MetricScope = proto.Field( + proto.ENUM, + number=6, + enum=MetricScope, + ) + restricted_metric_type: MutableSequence[RestrictedMetricType] = proto.RepeatedField( + proto.ENUM, + number=8, + enum=RestrictedMetricType, + ) + + +class DataRetentionSettings(proto.Message): + r"""Settings values for data retention. This is a singleton + resource. + + Attributes: + name (str): + Output only. Resource name for this + DataRetentionSetting resource. Format: + properties/{property}/dataRetentionSettings + event_data_retention (google.analytics.admin_v1beta.types.DataRetentionSettings.RetentionDuration): + The length of time that event-level data is + retained. + reset_user_data_on_new_activity (bool): + If true, reset the retention period for the + user identifier with every event from that user. + """ + class RetentionDuration(proto.Enum): + r"""Valid values for the data retention duration. + + Values: + RETENTION_DURATION_UNSPECIFIED (0): + Data retention time duration is not + specified. + TWO_MONTHS (1): + The data retention time duration is 2 months. + FOURTEEN_MONTHS (3): + The data retention time duration is 14 + months. + TWENTY_SIX_MONTHS (4): + The data retention time duration is 26 + months. Available to 360 properties only. + THIRTY_EIGHT_MONTHS (5): + The data retention time duration is 38 + months. Available to 360 properties only. + FIFTY_MONTHS (6): + The data retention time duration is 50 + months. Available to 360 properties only. + """ + RETENTION_DURATION_UNSPECIFIED = 0 + TWO_MONTHS = 1 + FOURTEEN_MONTHS = 3 + TWENTY_SIX_MONTHS = 4 + THIRTY_EIGHT_MONTHS = 5 + FIFTY_MONTHS = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + event_data_retention: RetentionDuration = proto.Field( + proto.ENUM, + number=2, + enum=RetentionDuration, + ) + reset_user_data_on_new_activity: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-analytics-admin/v1beta/mypy.ini b/owl-bot-staging/google-analytics-admin/v1beta/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-analytics-admin/v1beta/noxfile.py b/owl-bot-staging/google-analytics-admin/v1beta/noxfile.py new file mode 100644 index 000000000000..ba85558e9d83 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-analytics-admin' + +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) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/analytics/admin_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12"): + session.skip("cpp implementation is not supported in python 3.11+") + + # 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/analytics/admin_v1beta/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@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( + # TODO(https://github.com/googleapis/gapic-generator-python/issues/2066): + # Ignore release of mypy 1.11.0 which may have a regression + 'mypy!=1.11.0', + '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-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_async.py new file mode 100644 index 000000000000..e90fbd5bd010 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_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 AcknowledgeUserDataCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_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.analytics import admin_v1beta + + +async def sample_acknowledge_user_data_collection(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.AcknowledgeUserDataCollectionRequest( + property="property_value", + acknowledgement="acknowledgement_value", + ) + + # Make the request + response = await client.acknowledge_user_data_collection(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_sync.py new file mode 100644 index 000000000000..7a86a204ec22 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_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 AcknowledgeUserDataCollection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_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.analytics import admin_v1beta + + +def sample_acknowledge_user_data_collection(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.AcknowledgeUserDataCollectionRequest( + property="property_value", + acknowledgement="acknowledgement_value", + ) + + # Make the request + response = client.acknowledge_user_data_collection(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_async.py new file mode 100644 index 000000000000..7754f336ff88 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_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 ArchiveCustomDimension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomDimension_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.analytics import admin_v1beta + + +async def sample_archive_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ArchiveCustomDimensionRequest( + name="name_value", + ) + + # Make the request + await client.archive_custom_dimension(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomDimension_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_sync.py new file mode 100644 index 000000000000..716327ad3c55 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_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 ArchiveCustomDimension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomDimension_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.analytics import admin_v1beta + + +def sample_archive_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ArchiveCustomDimensionRequest( + name="name_value", + ) + + # Make the request + client.archive_custom_dimension(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomDimension_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_async.py new file mode 100644 index 000000000000..eae450f833e2 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_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 ArchiveCustomMetric +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomMetric_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.analytics import admin_v1beta + + +async def sample_archive_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ArchiveCustomMetricRequest( + name="name_value", + ) + + # Make the request + await client.archive_custom_metric(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomMetric_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_sync.py new file mode 100644 index 000000000000..34e8f64b71a3 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_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 ArchiveCustomMetric +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomMetric_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.analytics import admin_v1beta + + +def sample_archive_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ArchiveCustomMetricRequest( + name="name_value", + ) + + # Make the request + client.archive_custom_metric(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomMetric_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_async.py new file mode 100644 index 000000000000..489fa0c42fbd --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversionEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateConversionEvent_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.analytics import admin_v1beta + + +async def sample_create_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateConversionEventRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_conversion_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateConversionEvent_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_sync.py new file mode 100644 index 000000000000..8adcf0aaad03 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateConversionEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateConversionEvent_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.analytics import admin_v1beta + + +def sample_create_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateConversionEventRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_conversion_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateConversionEvent_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_async.py new file mode 100644 index 000000000000..e274941096b6 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCustomDimension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomDimension_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.analytics import admin_v1beta + + +async def sample_create_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + custom_dimension = admin_v1beta.CustomDimension() + custom_dimension.parameter_name = "parameter_name_value" + custom_dimension.display_name = "display_name_value" + custom_dimension.scope = "ITEM" + + request = admin_v1beta.CreateCustomDimensionRequest( + parent="parent_value", + custom_dimension=custom_dimension, + ) + + # Make the request + response = await client.create_custom_dimension(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomDimension_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_sync.py new file mode 100644 index 000000000000..fbd991f24d3e --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCustomDimension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomDimension_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.analytics import admin_v1beta + + +def sample_create_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + custom_dimension = admin_v1beta.CustomDimension() + custom_dimension.parameter_name = "parameter_name_value" + custom_dimension.display_name = "display_name_value" + custom_dimension.scope = "ITEM" + + request = admin_v1beta.CreateCustomDimensionRequest( + parent="parent_value", + custom_dimension=custom_dimension, + ) + + # Make the request + response = client.create_custom_dimension(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomDimension_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_async.py new file mode 100644 index 000000000000..073ae9b82a31 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCustomMetric +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomMetric_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.analytics import admin_v1beta + + +async def sample_create_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + custom_metric = admin_v1beta.CustomMetric() + custom_metric.parameter_name = "parameter_name_value" + custom_metric.display_name = "display_name_value" + custom_metric.measurement_unit = "HOURS" + custom_metric.scope = "EVENT" + + request = admin_v1beta.CreateCustomMetricRequest( + parent="parent_value", + custom_metric=custom_metric, + ) + + # Make the request + response = await client.create_custom_metric(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomMetric_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_sync.py new file mode 100644 index 000000000000..d92ae5a8d474 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCustomMetric +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomMetric_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.analytics import admin_v1beta + + +def sample_create_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + custom_metric = admin_v1beta.CustomMetric() + custom_metric.parameter_name = "parameter_name_value" + custom_metric.display_name = "display_name_value" + custom_metric.measurement_unit = "HOURS" + custom_metric.scope = "EVENT" + + request = admin_v1beta.CreateCustomMetricRequest( + parent="parent_value", + custom_metric=custom_metric, + ) + + # Make the request + response = client.create_custom_metric(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomMetric_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_async.py new file mode 100644 index 000000000000..0c90c7e90710 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateDataStream_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.analytics import admin_v1beta + + +async def sample_create_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + data_stream = admin_v1beta.DataStream() + data_stream.type_ = "IOS_APP_DATA_STREAM" + + request = admin_v1beta.CreateDataStreamRequest( + parent="parent_value", + data_stream=data_stream, + ) + + # Make the request + response = await client.create_data_stream(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateDataStream_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_sync.py new file mode 100644 index 000000000000..a1dfbcee7d2e --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDataStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateDataStream_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.analytics import admin_v1beta + + +def sample_create_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + data_stream = admin_v1beta.DataStream() + data_stream.type_ = "IOS_APP_DATA_STREAM" + + request = admin_v1beta.CreateDataStreamRequest( + parent="parent_value", + data_stream=data_stream, + ) + + # Make the request + response = client.create_data_stream(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateDataStream_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_async.py new file mode 100644 index 000000000000..40ee52c6e739 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_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 CreateFirebaseLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateFirebaseLink_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.analytics import admin_v1beta + + +async def sample_create_firebase_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateFirebaseLinkRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_firebase_link(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateFirebaseLink_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_sync.py new file mode 100644 index 000000000000..9af75d58d9f1 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_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 CreateFirebaseLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateFirebaseLink_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.analytics import admin_v1beta + + +def sample_create_firebase_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateFirebaseLinkRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_firebase_link(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateFirebaseLink_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_async.py new file mode 100644 index 000000000000..9129c5cb9ab5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_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 CreateGoogleAdsLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateGoogleAdsLink_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.analytics import admin_v1beta + + +async def sample_create_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateGoogleAdsLinkRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_google_ads_link(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateGoogleAdsLink_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_sync.py new file mode 100644 index 000000000000..e10436afdd3a --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_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 CreateGoogleAdsLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateGoogleAdsLink_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.analytics import admin_v1beta + + +def sample_create_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.CreateGoogleAdsLinkRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_google_ads_link(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateGoogleAdsLink_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_async.py new file mode 100644 index 000000000000..c082dbe4e7bc --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateKeyEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateKeyEvent_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.analytics import admin_v1beta + + +async def sample_create_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + key_event = admin_v1beta.KeyEvent() + key_event.counting_method = "ONCE_PER_SESSION" + + request = admin_v1beta.CreateKeyEventRequest( + key_event=key_event, + parent="parent_value", + ) + + # Make the request + response = await client.create_key_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateKeyEvent_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_sync.py new file mode 100644 index 000000000000..eadd6a13a045 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateKeyEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateKeyEvent_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.analytics import admin_v1beta + + +def sample_create_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + key_event = admin_v1beta.KeyEvent() + key_event.counting_method = "ONCE_PER_SESSION" + + request = admin_v1beta.CreateKeyEventRequest( + key_event=key_event, + parent="parent_value", + ) + + # Make the request + response = client.create_key_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateKeyEvent_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_async.py new file mode 100644 index 000000000000..241a9c21941a --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMeasurementProtocolSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_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.analytics import admin_v1beta + + +async def sample_create_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + measurement_protocol_secret = admin_v1beta.MeasurementProtocolSecret() + measurement_protocol_secret.display_name = "display_name_value" + + request = admin_v1beta.CreateMeasurementProtocolSecretRequest( + parent="parent_value", + measurement_protocol_secret=measurement_protocol_secret, + ) + + # Make the request + response = await client.create_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_sync.py new file mode 100644 index 000000000000..71595040861c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateMeasurementProtocolSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_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.analytics import admin_v1beta + + +def sample_create_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + measurement_protocol_secret = admin_v1beta.MeasurementProtocolSecret() + measurement_protocol_secret.display_name = "display_name_value" + + request = admin_v1beta.CreateMeasurementProtocolSecretRequest( + parent="parent_value", + measurement_protocol_secret=measurement_protocol_secret, + ) + + # Make the request + response = client.create_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_property_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_property_async.py new file mode 100644 index 000000000000..e7de11cc933f --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_property_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProperty +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_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.analytics import admin_v1beta + + +async def sample_create_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + property = admin_v1beta.Property() + property.display_name = "display_name_value" + property.time_zone = "time_zone_value" + + request = admin_v1beta.CreatePropertyRequest( + property=property, + ) + + # Make the request + response = await client.create_property(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_property_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_property_sync.py new file mode 100644 index 000000000000..3cf242d46549 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_create_property_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateProperty +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_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.analytics import admin_v1beta + + +def sample_create_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + property = admin_v1beta.Property() + property.display_name = "display_name_value" + property.time_zone = "time_zone_value" + + request = admin_v1beta.CreatePropertyRequest( + property=property, + ) + + # Make the request + response = client.create_property(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_async.py new file mode 100644 index 000000000000..9d274012ef92 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_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 DeleteAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteAccount_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.analytics import admin_v1beta + + +async def sample_delete_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + await client.delete_account(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteAccount_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_sync.py new file mode 100644 index 000000000000..a2d9a5260b53 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_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 DeleteAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteAccount_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.analytics import admin_v1beta + + +def sample_delete_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteAccountRequest( + name="name_value", + ) + + # Make the request + client.delete_account(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteAccount_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_async.py new file mode 100644 index 000000000000..f2057ca4be5b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_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 DeleteConversionEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteConversionEvent_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.analytics import admin_v1beta + + +async def sample_delete_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteConversionEventRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversion_event(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteConversionEvent_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_sync.py new file mode 100644 index 000000000000..47c3790e6bca --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_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 DeleteConversionEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteConversionEvent_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.analytics import admin_v1beta + + +def sample_delete_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteConversionEventRequest( + name="name_value", + ) + + # Make the request + client.delete_conversion_event(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteConversionEvent_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_async.py new file mode 100644 index 000000000000..932f7e6360f6 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_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 DeleteDataStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteDataStream_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.analytics import admin_v1beta + + +async def sample_delete_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteDataStreamRequest( + name="name_value", + ) + + # Make the request + await client.delete_data_stream(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteDataStream_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_sync.py new file mode 100644 index 000000000000..67fa631b4027 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_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 DeleteDataStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteDataStream_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.analytics import admin_v1beta + + +def sample_delete_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteDataStreamRequest( + name="name_value", + ) + + # Make the request + client.delete_data_stream(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteDataStream_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_async.py new file mode 100644 index 000000000000..b67b8fde5c3e --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_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 DeleteFirebaseLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteFirebaseLink_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.analytics import admin_v1beta + + +async def sample_delete_firebase_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteFirebaseLinkRequest( + name="name_value", + ) + + # Make the request + await client.delete_firebase_link(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteFirebaseLink_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_sync.py new file mode 100644 index 000000000000..2582cf39bbcb --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_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 DeleteFirebaseLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteFirebaseLink_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.analytics import admin_v1beta + + +def sample_delete_firebase_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteFirebaseLinkRequest( + name="name_value", + ) + + # Make the request + client.delete_firebase_link(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteFirebaseLink_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_async.py new file mode 100644 index 000000000000..0f849068a267 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_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 DeleteGoogleAdsLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteGoogleAdsLink_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.analytics import admin_v1beta + + +async def sample_delete_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteGoogleAdsLinkRequest( + name="name_value", + ) + + # Make the request + await client.delete_google_ads_link(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteGoogleAdsLink_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_sync.py new file mode 100644 index 000000000000..fd6af2ec0690 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_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 DeleteGoogleAdsLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteGoogleAdsLink_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.analytics import admin_v1beta + + +def sample_delete_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteGoogleAdsLinkRequest( + name="name_value", + ) + + # Make the request + client.delete_google_ads_link(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteGoogleAdsLink_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_async.py new file mode 100644 index 000000000000..754e273f5109 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_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 DeleteKeyEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteKeyEvent_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.analytics import admin_v1beta + + +async def sample_delete_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteKeyEventRequest( + name="name_value", + ) + + # Make the request + await client.delete_key_event(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteKeyEvent_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_sync.py new file mode 100644 index 000000000000..1f913cba3d96 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_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 DeleteKeyEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteKeyEvent_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.analytics import admin_v1beta + + +def sample_delete_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteKeyEventRequest( + name="name_value", + ) + + # Make the request + client.delete_key_event(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteKeyEvent_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_async.py new file mode 100644 index 000000000000..1a080326a314 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_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 DeleteMeasurementProtocolSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_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.analytics import admin_v1beta + + +async def sample_delete_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteMeasurementProtocolSecretRequest( + name="name_value", + ) + + # Make the request + await client.delete_measurement_protocol_secret(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_sync.py new file mode 100644 index 000000000000..5d62b52519e5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_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 DeleteMeasurementProtocolSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_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.analytics import admin_v1beta + + +def sample_delete_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeleteMeasurementProtocolSecretRequest( + name="name_value", + ) + + # Make the request + client.delete_measurement_protocol_secret(request=request) + + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_async.py new file mode 100644 index 000000000000..26bee0fc188a --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_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 DeleteProperty +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteProperty_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.analytics import admin_v1beta + + +async def sample_delete_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.DeletePropertyRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_property(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteProperty_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_sync.py new file mode 100644 index 000000000000..22201d8a43d8 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_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 DeleteProperty +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteProperty_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.analytics import admin_v1beta + + +def sample_delete_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.DeletePropertyRequest( + name="name_value", + ) + + # Make the request + response = client.delete_property(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteProperty_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_account_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_account_async.py new file mode 100644 index 000000000000..9d8a7ade05c2 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_account_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 GetAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetAccount_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.analytics import admin_v1beta + + +async def sample_get_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = await client.get_account(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetAccount_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_account_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_account_sync.py new file mode 100644 index 000000000000..e405d87ef4d9 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_account_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 GetAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetAccount_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.analytics import admin_v1beta + + +def sample_get_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetAccountRequest( + name="name_value", + ) + + # Make the request + response = client.get_account(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetAccount_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_async.py new file mode 100644 index 000000000000..b6d8b9812bbd --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversionEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetConversionEvent_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.analytics import admin_v1beta + + +async def sample_get_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetConversionEventRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversion_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetConversionEvent_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_sync.py new file mode 100644 index 000000000000..bf55b2b858e9 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversionEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetConversionEvent_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.analytics import admin_v1beta + + +def sample_get_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetConversionEventRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversion_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetConversionEvent_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_async.py new file mode 100644 index 000000000000..f2ac8987f0f4 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_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 GetCustomDimension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomDimension_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.analytics import admin_v1beta + + +async def sample_get_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetCustomDimensionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_custom_dimension(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomDimension_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_sync.py new file mode 100644 index 000000000000..45fe60a1c182 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_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 GetCustomDimension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomDimension_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.analytics import admin_v1beta + + +def sample_get_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetCustomDimensionRequest( + name="name_value", + ) + + # Make the request + response = client.get_custom_dimension(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomDimension_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_async.py new file mode 100644 index 000000000000..0344eb57ae39 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_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 GetCustomMetric +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomMetric_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.analytics import admin_v1beta + + +async def sample_get_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetCustomMetricRequest( + name="name_value", + ) + + # Make the request + response = await client.get_custom_metric(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomMetric_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_sync.py new file mode 100644 index 000000000000..717dd309995b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_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 GetCustomMetric +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomMetric_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.analytics import admin_v1beta + + +def sample_get_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetCustomMetricRequest( + name="name_value", + ) + + # Make the request + response = client.get_custom_metric(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomMetric_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_async.py new file mode 100644 index 000000000000..58382ea89361 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_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 GetDataRetentionSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataRetentionSettings_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.analytics import admin_v1beta + + +async def sample_get_data_retention_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataRetentionSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_retention_settings(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataRetentionSettings_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_sync.py new file mode 100644 index 000000000000..ffb469036489 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_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 GetDataRetentionSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataRetentionSettings_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.analytics import admin_v1beta + + +def sample_get_data_retention_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataRetentionSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_retention_settings(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataRetentionSettings_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_async.py new file mode 100644 index 000000000000..43a6a86b4b0c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_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 GetDataSharingSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataSharingSettings_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.analytics import admin_v1beta + + +async def sample_get_data_sharing_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataSharingSettingsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_sharing_settings(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataSharingSettings_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_sync.py new file mode 100644 index 000000000000..91c19d7b750b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_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 GetDataSharingSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataSharingSettings_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.analytics import admin_v1beta + + +def sample_get_data_sharing_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataSharingSettingsRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_sharing_settings(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataSharingSettings_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_async.py new file mode 100644 index 000000000000..f362b9bcf705 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataStream_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.analytics import admin_v1beta + + +async def sample_get_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataStreamRequest( + name="name_value", + ) + + # Make the request + response = await client.get_data_stream(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataStream_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_sync.py new file mode 100644 index 000000000000..cdbeb5e8cbde --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDataStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataStream_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.analytics import admin_v1beta + + +def sample_get_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetDataStreamRequest( + name="name_value", + ) + + # Make the request + response = client.get_data_stream(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataStream_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_async.py new file mode 100644 index 000000000000..b433bbd5e94b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetKeyEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetKeyEvent_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.analytics import admin_v1beta + + +async def sample_get_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetKeyEventRequest( + name="name_value", + ) + + # Make the request + response = await client.get_key_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetKeyEvent_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_sync.py new file mode 100644 index 000000000000..46211a76a6f4 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetKeyEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetKeyEvent_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.analytics import admin_v1beta + + +def sample_get_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetKeyEventRequest( + name="name_value", + ) + + # Make the request + response = client.get_key_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetKeyEvent_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_async.py new file mode 100644 index 000000000000..6671e902aaa3 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_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 GetMeasurementProtocolSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_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.analytics import admin_v1beta + + +async def sample_get_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetMeasurementProtocolSecretRequest( + name="name_value", + ) + + # Make the request + response = await client.get_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_sync.py new file mode 100644 index 000000000000..2e5ac99d120d --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_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 GetMeasurementProtocolSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_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.analytics import admin_v1beta + + +def sample_get_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetMeasurementProtocolSecretRequest( + name="name_value", + ) + + # Make the request + response = client.get_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_property_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_property_async.py new file mode 100644 index 000000000000..c6a292aa1554 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_property_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 GetProperty +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetProperty_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.analytics import admin_v1beta + + +async def sample_get_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.GetPropertyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_property(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetProperty_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_property_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_property_sync.py new file mode 100644 index 000000000000..67e5c73c9ed0 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_get_property_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 GetProperty +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_GetProperty_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.analytics import admin_v1beta + + +def sample_get_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.GetPropertyRequest( + name="name_value", + ) + + # Make the request + response = client.get_property(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_GetProperty_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_async.py new file mode 100644 index 000000000000..2b5d3dd23d8b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_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 ListAccountSummaries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccountSummaries_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.analytics import admin_v1beta + + +async def sample_list_account_summaries(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListAccountSummariesRequest( + ) + + # Make the request + page_result = client.list_account_summaries(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccountSummaries_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_sync.py new file mode 100644 index 000000000000..168c703e6bb3 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_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 ListAccountSummaries +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccountSummaries_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.analytics import admin_v1beta + + +def sample_list_account_summaries(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListAccountSummariesRequest( + ) + + # Make the request + page_result = client.list_account_summaries(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccountSummaries_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_async.py new file mode 100644 index 000000000000..59a38afb485a --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_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 ListAccounts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccounts_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.analytics import admin_v1beta + + +async def sample_list_accounts(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccounts_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_sync.py new file mode 100644 index 000000000000..bae5cef7c72f --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_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 ListAccounts +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccounts_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.analytics import admin_v1beta + + +def sample_list_accounts(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListAccountsRequest( + ) + + # Make the request + page_result = client.list_accounts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccounts_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_async.py new file mode 100644 index 000000000000..5d5324bd3528 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversionEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListConversionEvents_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.analytics import admin_v1beta + + +async def sample_list_conversion_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListConversionEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversion_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListConversionEvents_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_sync.py new file mode 100644 index 000000000000..ccaf1e71bbc7 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversionEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListConversionEvents_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.analytics import admin_v1beta + + +def sample_list_conversion_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListConversionEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversion_events(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListConversionEvents_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_async.py new file mode 100644 index 000000000000..585cebd093f4 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_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 ListCustomDimensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomDimensions_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.analytics import admin_v1beta + + +async def sample_list_custom_dimensions(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListCustomDimensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_dimensions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomDimensions_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_sync.py new file mode 100644 index 000000000000..d7e6ae54d67a --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_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 ListCustomDimensions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomDimensions_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.analytics import admin_v1beta + + +def sample_list_custom_dimensions(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListCustomDimensionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_dimensions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomDimensions_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_async.py new file mode 100644 index 000000000000..f548290fd6b2 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_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 ListCustomMetrics +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomMetrics_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.analytics import admin_v1beta + + +async def sample_list_custom_metrics(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListCustomMetricsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_metrics(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomMetrics_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_sync.py new file mode 100644 index 000000000000..a97ed0a275ef --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_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 ListCustomMetrics +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomMetrics_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.analytics import admin_v1beta + + +def sample_list_custom_metrics(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListCustomMetricsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_custom_metrics(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomMetrics_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_async.py new file mode 100644 index 000000000000..f6b8be1e98f4 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataStreams +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListDataStreams_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.analytics import admin_v1beta + + +async def sample_list_data_streams(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListDataStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_streams(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListDataStreams_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_sync.py new file mode 100644 index 000000000000..61a67339ca7b --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDataStreams +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListDataStreams_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.analytics import admin_v1beta + + +def sample_list_data_streams(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListDataStreamsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_data_streams(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListDataStreams_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_async.py new file mode 100644 index 000000000000..28f8c12b2298 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_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 ListFirebaseLinks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListFirebaseLinks_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.analytics import admin_v1beta + + +async def sample_list_firebase_links(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListFirebaseLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_firebase_links(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListFirebaseLinks_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_sync.py new file mode 100644 index 000000000000..29d2524f7500 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_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 ListFirebaseLinks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListFirebaseLinks_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.analytics import admin_v1beta + + +def sample_list_firebase_links(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListFirebaseLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_firebase_links(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListFirebaseLinks_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_async.py new file mode 100644 index 000000000000..917702b484b9 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_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 ListGoogleAdsLinks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListGoogleAdsLinks_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.analytics import admin_v1beta + + +async def sample_list_google_ads_links(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListGoogleAdsLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_ads_links(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListGoogleAdsLinks_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_sync.py new file mode 100644 index 000000000000..4a15b50f56e8 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_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 ListGoogleAdsLinks +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListGoogleAdsLinks_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.analytics import admin_v1beta + + +def sample_list_google_ads_links(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListGoogleAdsLinksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_google_ads_links(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListGoogleAdsLinks_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_async.py new file mode 100644 index 000000000000..0a4e3211c98f --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListKeyEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListKeyEvents_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.analytics import admin_v1beta + + +async def sample_list_key_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListKeyEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListKeyEvents_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_sync.py new file mode 100644 index 000000000000..e57b925302b6 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListKeyEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListKeyEvents_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.analytics import admin_v1beta + + +def sample_list_key_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListKeyEventsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_events(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListKeyEvents_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_async.py new file mode 100644 index 000000000000..25231520edcc --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_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 ListMeasurementProtocolSecrets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_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.analytics import admin_v1beta + + +async def sample_list_measurement_protocol_secrets(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListMeasurementProtocolSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_measurement_protocol_secrets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_sync.py new file mode 100644 index 000000000000..c608c7614e02 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_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 ListMeasurementProtocolSecrets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_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.analytics import admin_v1beta + + +def sample_list_measurement_protocol_secrets(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListMeasurementProtocolSecretsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_measurement_protocol_secrets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_async.py new file mode 100644 index 000000000000..6a875c0a2158 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_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 ListProperties +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListProperties_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.analytics import admin_v1beta + + +async def sample_list_properties(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ListPropertiesRequest( + filter="filter_value", + ) + + # Make the request + page_result = client.list_properties(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListProperties_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_sync.py new file mode 100644 index 000000000000..fa17bb382019 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_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 ListProperties +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ListProperties_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.analytics import admin_v1beta + + +def sample_list_properties(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ListPropertiesRequest( + filter="filter_value", + ) + + # Make the request + page_result = client.list_properties(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ListProperties_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_async.py new file mode 100644 index 000000000000..6393fb461f54 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_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 ProvisionAccountTicket +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ProvisionAccountTicket_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.analytics import admin_v1beta + + +async def sample_provision_account_ticket(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.ProvisionAccountTicketRequest( + ) + + # Make the request + response = await client.provision_account_ticket(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ProvisionAccountTicket_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_sync.py new file mode 100644 index 000000000000..bf1faf1533dd --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_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 ProvisionAccountTicket +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_ProvisionAccountTicket_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.analytics import admin_v1beta + + +def sample_provision_account_ticket(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.ProvisionAccountTicketRequest( + ) + + # Make the request + response = client.provision_account_ticket(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_ProvisionAccountTicket_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_async.py new file mode 100644 index 000000000000..892f3e146bf3 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_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 RunAccessReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_RunAccessReport_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.analytics import admin_v1beta + + +async def sample_run_access_report(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.RunAccessReportRequest( + ) + + # Make the request + response = await client.run_access_report(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_RunAccessReport_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_sync.py new file mode 100644 index 000000000000..74bfd3a8def5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_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 RunAccessReport +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_RunAccessReport_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.analytics import admin_v1beta + + +def sample_run_access_report(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.RunAccessReportRequest( + ) + + # Make the request + response = client.run_access_report(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_RunAccessReport_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_async.py new file mode 100644 index 000000000000..72a1166b53f2 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchChangeHistoryEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_SearchChangeHistoryEvents_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.analytics import admin_v1beta + + +async def sample_search_change_history_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.SearchChangeHistoryEventsRequest( + account="account_value", + ) + + # Make the request + page_result = client.search_change_history_events(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_SearchChangeHistoryEvents_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_sync.py new file mode 100644 index 000000000000..20d8c5158a43 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchChangeHistoryEvents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_SearchChangeHistoryEvents_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.analytics import admin_v1beta + + +def sample_search_change_history_events(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.SearchChangeHistoryEventsRequest( + account="account_value", + ) + + # Make the request + page_result = client.search_change_history_events(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_SearchChangeHistoryEvents_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_account_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_account_async.py new file mode 100644 index 000000000000..9078bd861280 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_account_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_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.analytics import admin_v1beta + + +async def sample_update_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + account = admin_v1beta.Account() + account.display_name = "display_name_value" + + request = admin_v1beta.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = await client.update_account(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_account_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_account_sync.py new file mode 100644 index 000000000000..de68cdf58ef8 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_account_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAccount +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_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.analytics import admin_v1beta + + +def sample_update_account(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + account = admin_v1beta.Account() + account.display_name = "display_name_value" + + request = admin_v1beta.UpdateAccountRequest( + account=account, + ) + + # Make the request + response = client.update_account(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_async.py new file mode 100644 index 000000000000..0f2102ea1cec --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_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 UpdateConversionEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateConversionEvent_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.analytics import admin_v1beta + + +async def sample_update_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateConversionEventRequest( + ) + + # Make the request + response = await client.update_conversion_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateConversionEvent_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_sync.py new file mode 100644 index 000000000000..93499bda6654 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_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 UpdateConversionEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateConversionEvent_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.analytics import admin_v1beta + + +def sample_update_conversion_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateConversionEventRequest( + ) + + # Make the request + response = client.update_conversion_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateConversionEvent_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_async.py new file mode 100644 index 000000000000..7255560356bf --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_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 UpdateCustomDimension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomDimension_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.analytics import admin_v1beta + + +async def sample_update_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateCustomDimensionRequest( + ) + + # Make the request + response = await client.update_custom_dimension(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomDimension_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_sync.py new file mode 100644 index 000000000000..2160f41fea48 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_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 UpdateCustomDimension +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomDimension_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.analytics import admin_v1beta + + +def sample_update_custom_dimension(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateCustomDimensionRequest( + ) + + # Make the request + response = client.update_custom_dimension(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomDimension_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_async.py new file mode 100644 index 000000000000..13959a26dcdf --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_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 UpdateCustomMetric +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomMetric_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.analytics import admin_v1beta + + +async def sample_update_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateCustomMetricRequest( + ) + + # Make the request + response = await client.update_custom_metric(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomMetric_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_sync.py new file mode 100644 index 000000000000..9966ecc38e8c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_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 UpdateCustomMetric +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomMetric_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.analytics import admin_v1beta + + +def sample_update_custom_metric(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateCustomMetricRequest( + ) + + # Make the request + response = client.update_custom_metric(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomMetric_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_async.py new file mode 100644 index 000000000000..61997c77c6f5 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_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 UpdateDataRetentionSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataRetentionSettings_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.analytics import admin_v1beta + + +async def sample_update_data_retention_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateDataRetentionSettingsRequest( + ) + + # Make the request + response = await client.update_data_retention_settings(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataRetentionSettings_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_sync.py new file mode 100644 index 000000000000..7a5997ec34c3 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_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 UpdateDataRetentionSettings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataRetentionSettings_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.analytics import admin_v1beta + + +def sample_update_data_retention_settings(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateDataRetentionSettingsRequest( + ) + + # Make the request + response = client.update_data_retention_settings(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataRetentionSettings_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_async.py new file mode 100644 index 000000000000..56fd96f25b08 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_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 UpdateDataStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataStream_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.analytics import admin_v1beta + + +async def sample_update_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateDataStreamRequest( + ) + + # Make the request + response = await client.update_data_stream(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataStream_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_sync.py new file mode 100644 index 000000000000..6fa73824b150 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_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 UpdateDataStream +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataStream_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.analytics import admin_v1beta + + +def sample_update_data_stream(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateDataStreamRequest( + ) + + # Make the request + response = client.update_data_stream(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataStream_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_async.py new file mode 100644 index 000000000000..6995e9581227 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_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 UpdateGoogleAdsLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateGoogleAdsLink_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.analytics import admin_v1beta + + +async def sample_update_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateGoogleAdsLinkRequest( + ) + + # Make the request + response = await client.update_google_ads_link(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateGoogleAdsLink_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_sync.py new file mode 100644 index 000000000000..1a4c749c9ff9 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_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 UpdateGoogleAdsLink +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateGoogleAdsLink_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.analytics import admin_v1beta + + +def sample_update_google_ads_link(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + request = admin_v1beta.UpdateGoogleAdsLinkRequest( + ) + + # Make the request + response = client.update_google_ads_link(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateGoogleAdsLink_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_async.py new file mode 100644 index 000000000000..1d83231eab37 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateKeyEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateKeyEvent_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.analytics import admin_v1beta + + +async def sample_update_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + key_event = admin_v1beta.KeyEvent() + key_event.counting_method = "ONCE_PER_SESSION" + + request = admin_v1beta.UpdateKeyEventRequest( + key_event=key_event, + ) + + # Make the request + response = await client.update_key_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateKeyEvent_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_sync.py new file mode 100644 index 000000000000..c2842afd68ad --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateKeyEvent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateKeyEvent_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.analytics import admin_v1beta + + +def sample_update_key_event(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + key_event = admin_v1beta.KeyEvent() + key_event.counting_method = "ONCE_PER_SESSION" + + request = admin_v1beta.UpdateKeyEventRequest( + key_event=key_event, + ) + + # Make the request + response = client.update_key_event(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateKeyEvent_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_async.py new file mode 100644 index 000000000000..850df657156d --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMeasurementProtocolSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_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.analytics import admin_v1beta + + +async def sample_update_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + measurement_protocol_secret = admin_v1beta.MeasurementProtocolSecret() + measurement_protocol_secret.display_name = "display_name_value" + + request = admin_v1beta.UpdateMeasurementProtocolSecretRequest( + measurement_protocol_secret=measurement_protocol_secret, + ) + + # Make the request + response = await client.update_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_sync.py new file mode 100644 index 000000000000..31eb5e2c049d --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateMeasurementProtocolSecret +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_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.analytics import admin_v1beta + + +def sample_update_measurement_protocol_secret(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + measurement_protocol_secret = admin_v1beta.MeasurementProtocolSecret() + measurement_protocol_secret.display_name = "display_name_value" + + request = admin_v1beta.UpdateMeasurementProtocolSecretRequest( + measurement_protocol_secret=measurement_protocol_secret, + ) + + # Make the request + response = client.update_measurement_protocol_secret(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_property_async.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_property_async.py new file mode 100644 index 000000000000..cd0a19ee446c --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_property_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProperty +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateProperty_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.analytics import admin_v1beta + + +async def sample_update_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceAsyncClient() + + # Initialize request argument(s) + property = admin_v1beta.Property() + property.display_name = "display_name_value" + property.time_zone = "time_zone_value" + + request = admin_v1beta.UpdatePropertyRequest( + property=property, + ) + + # Make the request + response = await client.update_property(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateProperty_async] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_property_sync.py b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_property_sync.py new file mode 100644 index 000000000000..e103708092eb --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/analyticsadmin_v1beta_generated_analytics_admin_service_update_property_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateProperty +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-analytics-admin + + +# [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateProperty_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.analytics import admin_v1beta + + +def sample_update_property(): + # Create a client + client = admin_v1beta.AnalyticsAdminServiceClient() + + # Initialize request argument(s) + property = admin_v1beta.Property() + property.display_name = "display_name_value" + property.time_zone = "time_zone_value" + + request = admin_v1beta.UpdatePropertyRequest( + property=property, + ) + + # Make the request + response = client.update_property(request=request) + + # Handle the response + print(response) + +# [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateProperty_sync] diff --git a/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json new file mode 100644 index 000000000000..5b91879363a3 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/samples/generated_samples/snippet_metadata_google.analytics.admin.v1beta.json @@ -0,0 +1,8743 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.analytics.admin.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-analytics-admin", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.acknowledge_user_data_collection", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.AcknowledgeUserDataCollection", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "AcknowledgeUserDataCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.AcknowledgeUserDataCollectionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.AcknowledgeUserDataCollectionResponse", + "shortName": "acknowledge_user_data_collection" + }, + "description": "Sample for AcknowledgeUserDataCollection", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_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": "analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.acknowledge_user_data_collection", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.AcknowledgeUserDataCollection", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "AcknowledgeUserDataCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.AcknowledgeUserDataCollectionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.AcknowledgeUserDataCollectionResponse", + "shortName": "acknowledge_user_data_collection" + }, + "description": "Sample for AcknowledgeUserDataCollection", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_AcknowledgeUserDataCollection_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": "analyticsadmin_v1beta_generated_analytics_admin_service_acknowledge_user_data_collection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.archive_custom_dimension", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ArchiveCustomDimension", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ArchiveCustomDimension" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ArchiveCustomDimensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "archive_custom_dimension" + }, + "description": "Sample for ArchiveCustomDimension", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomDimension_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": "analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.archive_custom_dimension", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ArchiveCustomDimension", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ArchiveCustomDimension" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ArchiveCustomDimensionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "archive_custom_dimension" + }, + "description": "Sample for ArchiveCustomDimension", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomDimension_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": "analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_dimension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.archive_custom_metric", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ArchiveCustomMetric", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ArchiveCustomMetric" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ArchiveCustomMetricRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "archive_custom_metric" + }, + "description": "Sample for ArchiveCustomMetric", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomMetric_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": "analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.archive_custom_metric", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ArchiveCustomMetric", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ArchiveCustomMetric" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ArchiveCustomMetricRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "archive_custom_metric" + }, + "description": "Sample for ArchiveCustomMetric", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ArchiveCustomMetric_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": "analyticsadmin_v1beta_generated_analytics_admin_service_archive_custom_metric_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.create_conversion_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateConversionEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateConversionEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateConversionEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversion_event", + "type": "google.analytics.admin_v1beta.types.ConversionEvent" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.ConversionEvent", + "shortName": "create_conversion_event" + }, + "description": "Sample for CreateConversionEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateConversionEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.create_conversion_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateConversionEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateConversionEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateConversionEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "conversion_event", + "type": "google.analytics.admin_v1beta.types.ConversionEvent" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.ConversionEvent", + "shortName": "create_conversion_event" + }, + "description": "Sample for CreateConversionEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateConversionEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_create_conversion_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.create_custom_dimension", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateCustomDimension", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateCustomDimension" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateCustomDimensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "custom_dimension", + "type": "google.analytics.admin_v1beta.types.CustomDimension" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.CustomDimension", + "shortName": "create_custom_dimension" + }, + "description": "Sample for CreateCustomDimension", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomDimension_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.create_custom_dimension", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateCustomDimension", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateCustomDimension" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateCustomDimensionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "custom_dimension", + "type": "google.analytics.admin_v1beta.types.CustomDimension" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.CustomDimension", + "shortName": "create_custom_dimension" + }, + "description": "Sample for CreateCustomDimension", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomDimension_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_dimension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.create_custom_metric", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateCustomMetric", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateCustomMetric" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateCustomMetricRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "custom_metric", + "type": "google.analytics.admin_v1beta.types.CustomMetric" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.CustomMetric", + "shortName": "create_custom_metric" + }, + "description": "Sample for CreateCustomMetric", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomMetric_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.create_custom_metric", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateCustomMetric", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateCustomMetric" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateCustomMetricRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "custom_metric", + "type": "google.analytics.admin_v1beta.types.CustomMetric" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.CustomMetric", + "shortName": "create_custom_metric" + }, + "description": "Sample for CreateCustomMetric", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateCustomMetric_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_custom_metric_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.create_data_stream", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateDataStream", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateDataStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateDataStreamRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_stream", + "type": "google.analytics.admin_v1beta.types.DataStream" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.DataStream", + "shortName": "create_data_stream" + }, + "description": "Sample for CreateDataStream", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateDataStream_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.create_data_stream", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateDataStream", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateDataStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateDataStreamRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "data_stream", + "type": "google.analytics.admin_v1beta.types.DataStream" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.DataStream", + "shortName": "create_data_stream" + }, + "description": "Sample for CreateDataStream", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateDataStream_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_data_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.create_firebase_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateFirebaseLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateFirebaseLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateFirebaseLinkRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "firebase_link", + "type": "google.analytics.admin_v1beta.types.FirebaseLink" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.FirebaseLink", + "shortName": "create_firebase_link" + }, + "description": "Sample for CreateFirebaseLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateFirebaseLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.create_firebase_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateFirebaseLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateFirebaseLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateFirebaseLinkRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "firebase_link", + "type": "google.analytics.admin_v1beta.types.FirebaseLink" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.FirebaseLink", + "shortName": "create_firebase_link" + }, + "description": "Sample for CreateFirebaseLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateFirebaseLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_create_firebase_link_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.create_google_ads_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateGoogleAdsLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateGoogleAdsLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateGoogleAdsLinkRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "google_ads_link", + "type": "google.analytics.admin_v1beta.types.GoogleAdsLink" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.GoogleAdsLink", + "shortName": "create_google_ads_link" + }, + "description": "Sample for CreateGoogleAdsLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateGoogleAdsLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.create_google_ads_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateGoogleAdsLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateGoogleAdsLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateGoogleAdsLinkRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "google_ads_link", + "type": "google.analytics.admin_v1beta.types.GoogleAdsLink" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.GoogleAdsLink", + "shortName": "create_google_ads_link" + }, + "description": "Sample for CreateGoogleAdsLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateGoogleAdsLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_create_google_ads_link_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.create_key_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateKeyEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateKeyEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateKeyEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "key_event", + "type": "google.analytics.admin_v1beta.types.KeyEvent" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.KeyEvent", + "shortName": "create_key_event" + }, + "description": "Sample for CreateKeyEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateKeyEvent_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.create_key_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateKeyEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateKeyEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateKeyEventRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "key_event", + "type": "google.analytics.admin_v1beta.types.KeyEvent" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.KeyEvent", + "shortName": "create_key_event" + }, + "description": "Sample for CreateKeyEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateKeyEvent_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_key_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.create_measurement_protocol_secret", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateMeasurementProtocolSecret", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateMeasurementProtocolSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateMeasurementProtocolSecretRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "measurement_protocol_secret", + "type": "google.analytics.admin_v1beta.types.MeasurementProtocolSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.MeasurementProtocolSecret", + "shortName": "create_measurement_protocol_secret" + }, + "description": "Sample for CreateMeasurementProtocolSecret", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.create_measurement_protocol_secret", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateMeasurementProtocolSecret", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateMeasurementProtocolSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreateMeasurementProtocolSecretRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "measurement_protocol_secret", + "type": "google.analytics.admin_v1beta.types.MeasurementProtocolSecret" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.MeasurementProtocolSecret", + "shortName": "create_measurement_protocol_secret" + }, + "description": "Sample for CreateMeasurementProtocolSecret", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateMeasurementProtocolSecret_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_measurement_protocol_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.create_property", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateProperty", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateProperty" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreatePropertyRequest" + }, + { + "name": "property", + "type": "google.analytics.admin_v1beta.types.Property" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.Property", + "shortName": "create_property" + }, + "description": "Sample for CreateProperty", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_property_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_property_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.create_property", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.CreateProperty", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "CreateProperty" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.CreatePropertyRequest" + }, + { + "name": "property", + "type": "google.analytics.admin_v1beta.types.Property" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.Property", + "shortName": "create_property" + }, + "description": "Sample for CreateProperty", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_create_property_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_CreateProperty_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_create_property_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.delete_account", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteAccount", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteAccountRequest" + }, + { + "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_account" + }, + "description": "Sample for DeleteAccount", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteAccount_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.delete_account", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteAccount", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteAccountRequest" + }, + { + "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_account" + }, + "description": "Sample for DeleteAccount", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteAccount_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.delete_conversion_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteConversionEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteConversionEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteConversionEventRequest" + }, + { + "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_conversion_event" + }, + "description": "Sample for DeleteConversionEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteConversionEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.delete_conversion_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteConversionEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteConversionEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteConversionEventRequest" + }, + { + "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_conversion_event" + }, + "description": "Sample for DeleteConversionEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteConversionEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_conversion_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.delete_data_stream", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteDataStream", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteDataStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteDataStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_data_stream" + }, + "description": "Sample for DeleteDataStream", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteDataStream_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.delete_data_stream", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteDataStream", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteDataStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteDataStreamRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_data_stream" + }, + "description": "Sample for DeleteDataStream", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteDataStream_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_data_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.delete_firebase_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteFirebaseLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteFirebaseLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteFirebaseLinkRequest" + }, + { + "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_firebase_link" + }, + "description": "Sample for DeleteFirebaseLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteFirebaseLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.delete_firebase_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteFirebaseLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteFirebaseLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteFirebaseLinkRequest" + }, + { + "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_firebase_link" + }, + "description": "Sample for DeleteFirebaseLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteFirebaseLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_firebase_link_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.delete_google_ads_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteGoogleAdsLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteGoogleAdsLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteGoogleAdsLinkRequest" + }, + { + "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_google_ads_link" + }, + "description": "Sample for DeleteGoogleAdsLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteGoogleAdsLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.delete_google_ads_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteGoogleAdsLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteGoogleAdsLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteGoogleAdsLinkRequest" + }, + { + "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_google_ads_link" + }, + "description": "Sample for DeleteGoogleAdsLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteGoogleAdsLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_google_ads_link_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.delete_key_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteKeyEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteKeyEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteKeyEventRequest" + }, + { + "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_key_event" + }, + "description": "Sample for DeleteKeyEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteKeyEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.delete_key_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteKeyEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteKeyEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteKeyEventRequest" + }, + { + "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_key_event" + }, + "description": "Sample for DeleteKeyEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteKeyEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_key_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.delete_measurement_protocol_secret", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteMeasurementProtocolSecret", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteMeasurementProtocolSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteMeasurementProtocolSecretRequest" + }, + { + "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_measurement_protocol_secret" + }, + "description": "Sample for DeleteMeasurementProtocolSecret", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.delete_measurement_protocol_secret", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteMeasurementProtocolSecret", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteMeasurementProtocolSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeleteMeasurementProtocolSecretRequest" + }, + { + "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_measurement_protocol_secret" + }, + "description": "Sample for DeleteMeasurementProtocolSecret", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_measurement_protocol_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.delete_property", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteProperty", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteProperty" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeletePropertyRequest" + }, + { + "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.analytics.admin_v1beta.types.Property", + "shortName": "delete_property" + }, + "description": "Sample for DeleteProperty", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteProperty_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.delete_property", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.DeleteProperty", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "DeleteProperty" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.DeletePropertyRequest" + }, + { + "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.analytics.admin_v1beta.types.Property", + "shortName": "delete_property" + }, + "description": "Sample for DeleteProperty", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_DeleteProperty_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": "analyticsadmin_v1beta_generated_analytics_admin_service_delete_property_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_account", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetAccount", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetAccountRequest" + }, + { + "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.analytics.admin_v1beta.types.Account", + "shortName": "get_account" + }, + "description": "Sample for GetAccount", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetAccount_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_account", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetAccount", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetAccountRequest" + }, + { + "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.analytics.admin_v1beta.types.Account", + "shortName": "get_account" + }, + "description": "Sample for GetAccount", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetAccount_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_conversion_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetConversionEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetConversionEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetConversionEventRequest" + }, + { + "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.analytics.admin_v1beta.types.ConversionEvent", + "shortName": "get_conversion_event" + }, + "description": "Sample for GetConversionEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetConversionEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_conversion_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetConversionEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetConversionEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetConversionEventRequest" + }, + { + "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.analytics.admin_v1beta.types.ConversionEvent", + "shortName": "get_conversion_event" + }, + "description": "Sample for GetConversionEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetConversionEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_conversion_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_custom_dimension", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetCustomDimension", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetCustomDimension" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetCustomDimensionRequest" + }, + { + "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.analytics.admin_v1beta.types.CustomDimension", + "shortName": "get_custom_dimension" + }, + "description": "Sample for GetCustomDimension", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomDimension_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_custom_dimension", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetCustomDimension", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetCustomDimension" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetCustomDimensionRequest" + }, + { + "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.analytics.admin_v1beta.types.CustomDimension", + "shortName": "get_custom_dimension" + }, + "description": "Sample for GetCustomDimension", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomDimension_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_dimension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_custom_metric", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetCustomMetric", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetCustomMetric" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetCustomMetricRequest" + }, + { + "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.analytics.admin_v1beta.types.CustomMetric", + "shortName": "get_custom_metric" + }, + "description": "Sample for GetCustomMetric", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomMetric_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_custom_metric", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetCustomMetric", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetCustomMetric" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetCustomMetricRequest" + }, + { + "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.analytics.admin_v1beta.types.CustomMetric", + "shortName": "get_custom_metric" + }, + "description": "Sample for GetCustomMetric", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetCustomMetric_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_custom_metric_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_data_retention_settings", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetDataRetentionSettings", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetDataRetentionSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetDataRetentionSettingsRequest" + }, + { + "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.analytics.admin_v1beta.types.DataRetentionSettings", + "shortName": "get_data_retention_settings" + }, + "description": "Sample for GetDataRetentionSettings", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataRetentionSettings_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_data_retention_settings", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetDataRetentionSettings", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetDataRetentionSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetDataRetentionSettingsRequest" + }, + { + "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.analytics.admin_v1beta.types.DataRetentionSettings", + "shortName": "get_data_retention_settings" + }, + "description": "Sample for GetDataRetentionSettings", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataRetentionSettings_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_retention_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_data_sharing_settings", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetDataSharingSettings", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetDataSharingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetDataSharingSettingsRequest" + }, + { + "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.analytics.admin_v1beta.types.DataSharingSettings", + "shortName": "get_data_sharing_settings" + }, + "description": "Sample for GetDataSharingSettings", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataSharingSettings_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_data_sharing_settings", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetDataSharingSettings", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetDataSharingSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetDataSharingSettingsRequest" + }, + { + "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.analytics.admin_v1beta.types.DataSharingSettings", + "shortName": "get_data_sharing_settings" + }, + "description": "Sample for GetDataSharingSettings", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataSharingSettings_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_sharing_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_data_stream", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetDataStream", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetDataStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetDataStreamRequest" + }, + { + "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.analytics.admin_v1beta.types.DataStream", + "shortName": "get_data_stream" + }, + "description": "Sample for GetDataStream", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataStream_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_data_stream", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetDataStream", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetDataStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetDataStreamRequest" + }, + { + "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.analytics.admin_v1beta.types.DataStream", + "shortName": "get_data_stream" + }, + "description": "Sample for GetDataStream", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetDataStream_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_data_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_key_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetKeyEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetKeyEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetKeyEventRequest" + }, + { + "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.analytics.admin_v1beta.types.KeyEvent", + "shortName": "get_key_event" + }, + "description": "Sample for GetKeyEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetKeyEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_key_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetKeyEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetKeyEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetKeyEventRequest" + }, + { + "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.analytics.admin_v1beta.types.KeyEvent", + "shortName": "get_key_event" + }, + "description": "Sample for GetKeyEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetKeyEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_key_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_measurement_protocol_secret", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetMeasurementProtocolSecret", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetMeasurementProtocolSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetMeasurementProtocolSecretRequest" + }, + { + "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.analytics.admin_v1beta.types.MeasurementProtocolSecret", + "shortName": "get_measurement_protocol_secret" + }, + "description": "Sample for GetMeasurementProtocolSecret", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_measurement_protocol_secret", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetMeasurementProtocolSecret", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetMeasurementProtocolSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetMeasurementProtocolSecretRequest" + }, + { + "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.analytics.admin_v1beta.types.MeasurementProtocolSecret", + "shortName": "get_measurement_protocol_secret" + }, + "description": "Sample for GetMeasurementProtocolSecret", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetMeasurementProtocolSecret_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_measurement_protocol_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.get_property", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetProperty", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetProperty" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetPropertyRequest" + }, + { + "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.analytics.admin_v1beta.types.Property", + "shortName": "get_property" + }, + "description": "Sample for GetProperty", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_property_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetProperty_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_property_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.get_property", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.GetProperty", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "GetProperty" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.GetPropertyRequest" + }, + { + "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.analytics.admin_v1beta.types.Property", + "shortName": "get_property" + }, + "description": "Sample for GetProperty", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_get_property_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_GetProperty_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": "analyticsadmin_v1beta_generated_analytics_admin_service_get_property_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_account_summaries", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListAccountSummaries", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListAccountSummaries" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListAccountSummariesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListAccountSummariesAsyncPager", + "shortName": "list_account_summaries" + }, + "description": "Sample for ListAccountSummaries", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccountSummaries_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_account_summaries", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListAccountSummaries", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListAccountSummaries" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListAccountSummariesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListAccountSummariesPager", + "shortName": "list_account_summaries" + }, + "description": "Sample for ListAccountSummaries", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccountSummaries_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_account_summaries_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_accounts", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListAccounts", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListAccountsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListAccountsAsyncPager", + "shortName": "list_accounts" + }, + "description": "Sample for ListAccounts", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccounts_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_accounts", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListAccounts", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListAccounts" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListAccountsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListAccountsPager", + "shortName": "list_accounts" + }, + "description": "Sample for ListAccounts", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListAccounts_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_accounts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_conversion_events", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListConversionEvents", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListConversionEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListConversionEventsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListConversionEventsAsyncPager", + "shortName": "list_conversion_events" + }, + "description": "Sample for ListConversionEvents", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListConversionEvents_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_conversion_events", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListConversionEvents", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListConversionEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListConversionEventsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListConversionEventsPager", + "shortName": "list_conversion_events" + }, + "description": "Sample for ListConversionEvents", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListConversionEvents_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_conversion_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_custom_dimensions", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListCustomDimensions", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListCustomDimensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListCustomDimensionsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListCustomDimensionsAsyncPager", + "shortName": "list_custom_dimensions" + }, + "description": "Sample for ListCustomDimensions", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomDimensions_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_custom_dimensions", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListCustomDimensions", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListCustomDimensions" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListCustomDimensionsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListCustomDimensionsPager", + "shortName": "list_custom_dimensions" + }, + "description": "Sample for ListCustomDimensions", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomDimensions_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_dimensions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_custom_metrics", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListCustomMetrics", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListCustomMetrics" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListCustomMetricsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListCustomMetricsAsyncPager", + "shortName": "list_custom_metrics" + }, + "description": "Sample for ListCustomMetrics", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomMetrics_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_custom_metrics", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListCustomMetrics", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListCustomMetrics" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListCustomMetricsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListCustomMetricsPager", + "shortName": "list_custom_metrics" + }, + "description": "Sample for ListCustomMetrics", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListCustomMetrics_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_custom_metrics_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_data_streams", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListDataStreams", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListDataStreams" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListDataStreamsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListDataStreamsAsyncPager", + "shortName": "list_data_streams" + }, + "description": "Sample for ListDataStreams", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListDataStreams_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_data_streams", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListDataStreams", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListDataStreams" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListDataStreamsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListDataStreamsPager", + "shortName": "list_data_streams" + }, + "description": "Sample for ListDataStreams", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListDataStreams_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_data_streams_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_firebase_links", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListFirebaseLinks", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListFirebaseLinks" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListFirebaseLinksRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListFirebaseLinksAsyncPager", + "shortName": "list_firebase_links" + }, + "description": "Sample for ListFirebaseLinks", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListFirebaseLinks_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_firebase_links", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListFirebaseLinks", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListFirebaseLinks" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListFirebaseLinksRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListFirebaseLinksPager", + "shortName": "list_firebase_links" + }, + "description": "Sample for ListFirebaseLinks", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListFirebaseLinks_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_firebase_links_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_google_ads_links", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListGoogleAdsLinks", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListGoogleAdsLinks" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListGoogleAdsLinksRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListGoogleAdsLinksAsyncPager", + "shortName": "list_google_ads_links" + }, + "description": "Sample for ListGoogleAdsLinks", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListGoogleAdsLinks_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_google_ads_links", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListGoogleAdsLinks", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListGoogleAdsLinks" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListGoogleAdsLinksRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListGoogleAdsLinksPager", + "shortName": "list_google_ads_links" + }, + "description": "Sample for ListGoogleAdsLinks", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListGoogleAdsLinks_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_google_ads_links_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_key_events", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListKeyEvents", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListKeyEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListKeyEventsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListKeyEventsAsyncPager", + "shortName": "list_key_events" + }, + "description": "Sample for ListKeyEvents", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListKeyEvents_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_key_events", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListKeyEvents", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListKeyEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListKeyEventsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListKeyEventsPager", + "shortName": "list_key_events" + }, + "description": "Sample for ListKeyEvents", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListKeyEvents_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_key_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_measurement_protocol_secrets", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListMeasurementProtocolSecrets", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListMeasurementProtocolSecrets" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListMeasurementProtocolSecretsAsyncPager", + "shortName": "list_measurement_protocol_secrets" + }, + "description": "Sample for ListMeasurementProtocolSecrets", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_measurement_protocol_secrets", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListMeasurementProtocolSecrets", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListMeasurementProtocolSecrets" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListMeasurementProtocolSecretsRequest" + }, + { + "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.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListMeasurementProtocolSecretsPager", + "shortName": "list_measurement_protocol_secrets" + }, + "description": "Sample for ListMeasurementProtocolSecrets", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListMeasurementProtocolSecrets_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_measurement_protocol_secrets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.list_properties", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListProperties", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListProperties" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListPropertiesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListPropertiesAsyncPager", + "shortName": "list_properties" + }, + "description": "Sample for ListProperties", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListProperties_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.list_properties", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ListProperties", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ListProperties" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ListPropertiesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.services.analytics_admin_service.pagers.ListPropertiesPager", + "shortName": "list_properties" + }, + "description": "Sample for ListProperties", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ListProperties_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": "analyticsadmin_v1beta_generated_analytics_admin_service_list_properties_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.provision_account_ticket", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ProvisionAccountTicket", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ProvisionAccountTicket" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ProvisionAccountTicketRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.ProvisionAccountTicketResponse", + "shortName": "provision_account_ticket" + }, + "description": "Sample for ProvisionAccountTicket", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ProvisionAccountTicket_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": "analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.provision_account_ticket", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.ProvisionAccountTicket", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "ProvisionAccountTicket" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.ProvisionAccountTicketRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.ProvisionAccountTicketResponse", + "shortName": "provision_account_ticket" + }, + "description": "Sample for ProvisionAccountTicket", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_ProvisionAccountTicket_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": "analyticsadmin_v1beta_generated_analytics_admin_service_provision_account_ticket_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.run_access_report", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.RunAccessReport", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "RunAccessReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.RunAccessReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.RunAccessReportResponse", + "shortName": "run_access_report" + }, + "description": "Sample for RunAccessReport", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_RunAccessReport_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": "analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.run_access_report", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.RunAccessReport", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "RunAccessReport" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.RunAccessReportRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.types.RunAccessReportResponse", + "shortName": "run_access_report" + }, + "description": "Sample for RunAccessReport", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_RunAccessReport_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": "analyticsadmin_v1beta_generated_analytics_admin_service_run_access_report_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.search_change_history_events", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.SearchChangeHistoryEvents", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "SearchChangeHistoryEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.SearchChangeHistoryEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.services.analytics_admin_service.pagers.SearchChangeHistoryEventsAsyncPager", + "shortName": "search_change_history_events" + }, + "description": "Sample for SearchChangeHistoryEvents", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_SearchChangeHistoryEvents_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": "analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.search_change_history_events", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.SearchChangeHistoryEvents", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "SearchChangeHistoryEvents" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.SearchChangeHistoryEventsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.analytics.admin_v1beta.services.analytics_admin_service.pagers.SearchChangeHistoryEventsPager", + "shortName": "search_change_history_events" + }, + "description": "Sample for SearchChangeHistoryEvents", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_SearchChangeHistoryEvents_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": "analyticsadmin_v1beta_generated_analytics_admin_service_search_change_history_events_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_account", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateAccount", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateAccountRequest" + }, + { + "name": "account", + "type": "google.analytics.admin_v1beta.types.Account" + }, + { + "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.analytics.admin_v1beta.types.Account", + "shortName": "update_account" + }, + "description": "Sample for UpdateAccount", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_account_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_update_account_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_account", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateAccount", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateAccount" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateAccountRequest" + }, + { + "name": "account", + "type": "google.analytics.admin_v1beta.types.Account" + }, + { + "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.analytics.admin_v1beta.types.Account", + "shortName": "update_account" + }, + "description": "Sample for UpdateAccount", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_account_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_update_account_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_conversion_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateConversionEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateConversionEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateConversionEventRequest" + }, + { + "name": "conversion_event", + "type": "google.analytics.admin_v1beta.types.ConversionEvent" + }, + { + "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.analytics.admin_v1beta.types.ConversionEvent", + "shortName": "update_conversion_event" + }, + "description": "Sample for UpdateConversionEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateConversionEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_conversion_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateConversionEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateConversionEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateConversionEventRequest" + }, + { + "name": "conversion_event", + "type": "google.analytics.admin_v1beta.types.ConversionEvent" + }, + { + "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.analytics.admin_v1beta.types.ConversionEvent", + "shortName": "update_conversion_event" + }, + "description": "Sample for UpdateConversionEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateConversionEvent_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_conversion_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_custom_dimension", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateCustomDimension", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateCustomDimension" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateCustomDimensionRequest" + }, + { + "name": "custom_dimension", + "type": "google.analytics.admin_v1beta.types.CustomDimension" + }, + { + "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.analytics.admin_v1beta.types.CustomDimension", + "shortName": "update_custom_dimension" + }, + "description": "Sample for UpdateCustomDimension", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomDimension_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_custom_dimension", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateCustomDimension", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateCustomDimension" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateCustomDimensionRequest" + }, + { + "name": "custom_dimension", + "type": "google.analytics.admin_v1beta.types.CustomDimension" + }, + { + "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.analytics.admin_v1beta.types.CustomDimension", + "shortName": "update_custom_dimension" + }, + "description": "Sample for UpdateCustomDimension", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomDimension_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_dimension_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_custom_metric", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateCustomMetric", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateCustomMetric" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateCustomMetricRequest" + }, + { + "name": "custom_metric", + "type": "google.analytics.admin_v1beta.types.CustomMetric" + }, + { + "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.analytics.admin_v1beta.types.CustomMetric", + "shortName": "update_custom_metric" + }, + "description": "Sample for UpdateCustomMetric", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomMetric_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_custom_metric", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateCustomMetric", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateCustomMetric" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateCustomMetricRequest" + }, + { + "name": "custom_metric", + "type": "google.analytics.admin_v1beta.types.CustomMetric" + }, + { + "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.analytics.admin_v1beta.types.CustomMetric", + "shortName": "update_custom_metric" + }, + "description": "Sample for UpdateCustomMetric", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateCustomMetric_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_custom_metric_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_data_retention_settings", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateDataRetentionSettings", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateDataRetentionSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateDataRetentionSettingsRequest" + }, + { + "name": "data_retention_settings", + "type": "google.analytics.admin_v1beta.types.DataRetentionSettings" + }, + { + "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.analytics.admin_v1beta.types.DataRetentionSettings", + "shortName": "update_data_retention_settings" + }, + "description": "Sample for UpdateDataRetentionSettings", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataRetentionSettings_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_data_retention_settings", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateDataRetentionSettings", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateDataRetentionSettings" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateDataRetentionSettingsRequest" + }, + { + "name": "data_retention_settings", + "type": "google.analytics.admin_v1beta.types.DataRetentionSettings" + }, + { + "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.analytics.admin_v1beta.types.DataRetentionSettings", + "shortName": "update_data_retention_settings" + }, + "description": "Sample for UpdateDataRetentionSettings", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataRetentionSettings_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_data_retention_settings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_data_stream", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateDataStream", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateDataStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateDataStreamRequest" + }, + { + "name": "data_stream", + "type": "google.analytics.admin_v1beta.types.DataStream" + }, + { + "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.analytics.admin_v1beta.types.DataStream", + "shortName": "update_data_stream" + }, + "description": "Sample for UpdateDataStream", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataStream_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_data_stream", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateDataStream", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateDataStream" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateDataStreamRequest" + }, + { + "name": "data_stream", + "type": "google.analytics.admin_v1beta.types.DataStream" + }, + { + "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.analytics.admin_v1beta.types.DataStream", + "shortName": "update_data_stream" + }, + "description": "Sample for UpdateDataStream", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateDataStream_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_data_stream_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_google_ads_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateGoogleAdsLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateGoogleAdsLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateGoogleAdsLinkRequest" + }, + { + "name": "google_ads_link", + "type": "google.analytics.admin_v1beta.types.GoogleAdsLink" + }, + { + "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.analytics.admin_v1beta.types.GoogleAdsLink", + "shortName": "update_google_ads_link" + }, + "description": "Sample for UpdateGoogleAdsLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateGoogleAdsLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_google_ads_link", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateGoogleAdsLink", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateGoogleAdsLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateGoogleAdsLinkRequest" + }, + { + "name": "google_ads_link", + "type": "google.analytics.admin_v1beta.types.GoogleAdsLink" + }, + { + "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.analytics.admin_v1beta.types.GoogleAdsLink", + "shortName": "update_google_ads_link" + }, + "description": "Sample for UpdateGoogleAdsLink", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateGoogleAdsLink_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": "analyticsadmin_v1beta_generated_analytics_admin_service_update_google_ads_link_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_key_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateKeyEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateKeyEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateKeyEventRequest" + }, + { + "name": "key_event", + "type": "google.analytics.admin_v1beta.types.KeyEvent" + }, + { + "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.analytics.admin_v1beta.types.KeyEvent", + "shortName": "update_key_event" + }, + "description": "Sample for UpdateKeyEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateKeyEvent_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_key_event", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateKeyEvent", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateKeyEvent" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateKeyEventRequest" + }, + { + "name": "key_event", + "type": "google.analytics.admin_v1beta.types.KeyEvent" + }, + { + "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.analytics.admin_v1beta.types.KeyEvent", + "shortName": "update_key_event" + }, + "description": "Sample for UpdateKeyEvent", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateKeyEvent_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_update_key_event_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_measurement_protocol_secret", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateMeasurementProtocolSecret", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateMeasurementProtocolSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateMeasurementProtocolSecretRequest" + }, + { + "name": "measurement_protocol_secret", + "type": "google.analytics.admin_v1beta.types.MeasurementProtocolSecret" + }, + { + "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.analytics.admin_v1beta.types.MeasurementProtocolSecret", + "shortName": "update_measurement_protocol_secret" + }, + "description": "Sample for UpdateMeasurementProtocolSecret", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_measurement_protocol_secret", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateMeasurementProtocolSecret", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateMeasurementProtocolSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdateMeasurementProtocolSecretRequest" + }, + { + "name": "measurement_protocol_secret", + "type": "google.analytics.admin_v1beta.types.MeasurementProtocolSecret" + }, + { + "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.analytics.admin_v1beta.types.MeasurementProtocolSecret", + "shortName": "update_measurement_protocol_secret" + }, + "description": "Sample for UpdateMeasurementProtocolSecret", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateMeasurementProtocolSecret_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_update_measurement_protocol_secret_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient", + "shortName": "AnalyticsAdminServiceAsyncClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceAsyncClient.update_property", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateProperty", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateProperty" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdatePropertyRequest" + }, + { + "name": "property", + "type": "google.analytics.admin_v1beta.types.Property" + }, + { + "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.analytics.admin_v1beta.types.Property", + "shortName": "update_property" + }, + "description": "Sample for UpdateProperty", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_property_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateProperty_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_update_property_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient", + "shortName": "AnalyticsAdminServiceClient" + }, + "fullName": "google.analytics.admin_v1beta.AnalyticsAdminServiceClient.update_property", + "method": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService.UpdateProperty", + "service": { + "fullName": "google.analytics.admin.v1beta.AnalyticsAdminService", + "shortName": "AnalyticsAdminService" + }, + "shortName": "UpdateProperty" + }, + "parameters": [ + { + "name": "request", + "type": "google.analytics.admin_v1beta.types.UpdatePropertyRequest" + }, + { + "name": "property", + "type": "google.analytics.admin_v1beta.types.Property" + }, + { + "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.analytics.admin_v1beta.types.Property", + "shortName": "update_property" + }, + "description": "Sample for UpdateProperty", + "file": "analyticsadmin_v1beta_generated_analytics_admin_service_update_property_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateProperty_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "analyticsadmin_v1beta_generated_analytics_admin_service_update_property_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-analytics-admin/v1beta/scripts/fixup_admin_v1beta_keywords.py b/owl-bot-staging/google-analytics-admin/v1beta/scripts/fixup_admin_v1beta_keywords.py new file mode 100644 index 000000000000..c169adbd2ef3 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/scripts/fixup_admin_v1beta_keywords.py @@ -0,0 +1,229 @@ +#! /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 adminCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'acknowledge_user_data_collection': ('property', 'acknowledgement', ), + 'archive_custom_dimension': ('name', ), + 'archive_custom_metric': ('name', ), + 'create_conversion_event': ('conversion_event', 'parent', ), + 'create_custom_dimension': ('parent', 'custom_dimension', ), + 'create_custom_metric': ('parent', 'custom_metric', ), + 'create_data_stream': ('parent', 'data_stream', ), + 'create_firebase_link': ('parent', 'firebase_link', ), + 'create_google_ads_link': ('parent', 'google_ads_link', ), + 'create_key_event': ('key_event', 'parent', ), + 'create_measurement_protocol_secret': ('parent', 'measurement_protocol_secret', ), + 'create_property': ('property', ), + 'delete_account': ('name', ), + 'delete_conversion_event': ('name', ), + 'delete_data_stream': ('name', ), + 'delete_firebase_link': ('name', ), + 'delete_google_ads_link': ('name', ), + 'delete_key_event': ('name', ), + 'delete_measurement_protocol_secret': ('name', ), + 'delete_property': ('name', ), + 'get_account': ('name', ), + 'get_conversion_event': ('name', ), + 'get_custom_dimension': ('name', ), + 'get_custom_metric': ('name', ), + 'get_data_retention_settings': ('name', ), + 'get_data_sharing_settings': ('name', ), + 'get_data_stream': ('name', ), + 'get_key_event': ('name', ), + 'get_measurement_protocol_secret': ('name', ), + 'get_property': ('name', ), + 'list_accounts': ('page_size', 'page_token', 'show_deleted', ), + 'list_account_summaries': ('page_size', 'page_token', ), + 'list_conversion_events': ('parent', 'page_size', 'page_token', ), + 'list_custom_dimensions': ('parent', 'page_size', 'page_token', ), + 'list_custom_metrics': ('parent', 'page_size', 'page_token', ), + 'list_data_streams': ('parent', 'page_size', 'page_token', ), + 'list_firebase_links': ('parent', 'page_size', 'page_token', ), + 'list_google_ads_links': ('parent', 'page_size', 'page_token', ), + 'list_key_events': ('parent', 'page_size', 'page_token', ), + 'list_measurement_protocol_secrets': ('parent', 'page_size', 'page_token', ), + 'list_properties': ('filter', 'page_size', 'page_token', 'show_deleted', ), + 'provision_account_ticket': ('account', 'redirect_uri', ), + 'run_access_report': ('entity', 'dimensions', 'metrics', 'date_ranges', 'dimension_filter', 'metric_filter', 'offset', 'limit', 'time_zone', 'order_bys', 'return_entity_quota', 'include_all_users', 'expand_groups', ), + 'search_change_history_events': ('account', 'property', 'resource_type', 'action', 'actor_email', 'earliest_change_time', 'latest_change_time', 'page_size', 'page_token', ), + 'update_account': ('account', 'update_mask', ), + 'update_conversion_event': ('conversion_event', 'update_mask', ), + 'update_custom_dimension': ('update_mask', 'custom_dimension', ), + 'update_custom_metric': ('update_mask', 'custom_metric', ), + 'update_data_retention_settings': ('data_retention_settings', 'update_mask', ), + 'update_data_stream': ('update_mask', 'data_stream', ), + 'update_google_ads_link': ('update_mask', 'google_ads_link', ), + 'update_key_event': ('key_event', 'update_mask', ), + 'update_measurement_protocol_secret': ('measurement_protocol_secret', 'update_mask', ), + 'update_property': ('property', 'update_mask', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=adminCallTransformer(), +): + """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 admin 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-analytics-admin/v1beta/setup.py b/owl-bot-staging/google-analytics-admin/v1beta/setup.py new file mode 100644 index 000000000000..7caf4766b048 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/setup.py @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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-analytics-admin' + + +description = "Google Analytics Admin API client library" + +version = None + +with open(os.path.join(package_root, 'google/analytics/admin/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.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-analytics-admin" + +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-analytics-admin/v1beta/testing/constraints-3.10.txt b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.11.txt b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.12.txt b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.7.txt b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.7.txt new file mode 100644 index 000000000000..fc812592b0ee --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# 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.20.2 diff --git a/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.8.txt b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.9.txt b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- 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 diff --git a/owl-bot-staging/google-analytics-admin/v1beta/tests/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/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-analytics-admin/v1beta/tests/unit/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/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-analytics-admin/v1beta/tests/unit/gapic/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/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-analytics-admin/v1beta/tests/unit/gapic/admin_v1beta/__init__.py b/owl-bot-staging/google-analytics-admin/v1beta/tests/unit/gapic/admin_v1beta/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/tests/unit/gapic/admin_v1beta/__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-analytics-admin/v1beta/tests/unit/gapic/admin_v1beta/test_analytics_admin_service.py b/owl-bot-staging/google-analytics-admin/v1beta/tests/unit/gapic/admin_v1beta/test_analytics_admin_service.py new file mode 100644 index 000000000000..ac332bdd4f99 --- /dev/null +++ b/owl-bot-staging/google-analytics-admin/v1beta/tests/unit/gapic/admin_v1beta/test_analytics_admin_service.py @@ -0,0 +1,38805 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.analytics.admin_v1beta.services.analytics_admin_service import AnalyticsAdminServiceAsyncClient +from google.analytics.admin_v1beta.services.analytics_admin_service import AnalyticsAdminServiceClient +from google.analytics.admin_v1beta.services.analytics_admin_service import pagers +from google.analytics.admin_v1beta.services.analytics_admin_service import transports +from google.analytics.admin_v1beta.types import access_report +from google.analytics.admin_v1beta.types import analytics_admin +from google.analytics.admin_v1beta.types import resources +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.api_core import retry as retries +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 +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 AnalyticsAdminServiceClient._get_default_mtls_endpoint(None) is None + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AnalyticsAdminServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AnalyticsAdminServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AnalyticsAdminServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AnalyticsAdminServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AnalyticsAdminServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AnalyticsAdminServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._get_client_cert_source(None, False) is None + assert AnalyticsAdminServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AnalyticsAdminServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AnalyticsAdminServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + default_endpoint = AnalyticsAdminServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AnalyticsAdminServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AnalyticsAdminServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AnalyticsAdminServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + assert AnalyticsAdminServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AnalyticsAdminServiceClient._get_api_endpoint(None, None, default_universe, "always") == AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + assert AnalyticsAdminServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AnalyticsAdminServiceClient.DEFAULT_MTLS_ENDPOINT + assert AnalyticsAdminServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AnalyticsAdminServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AnalyticsAdminServiceClient._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 AnalyticsAdminServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AnalyticsAdminServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AnalyticsAdminServiceClient._get_universe_domain(None, None) == AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AnalyticsAdminServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "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", [ + (AnalyticsAdminServiceClient, "grpc"), + (AnalyticsAdminServiceAsyncClient, "grpc_asyncio"), + (AnalyticsAdminServiceClient, "rest"), +]) +def test_analytics_admin_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 == ( + 'analyticsadmin.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://analyticsadmin.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AnalyticsAdminServiceGrpcTransport, "grpc"), + (transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AnalyticsAdminServiceRestTransport, "rest"), +]) +def test_analytics_admin_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", [ + (AnalyticsAdminServiceClient, "grpc"), + (AnalyticsAdminServiceAsyncClient, "grpc_asyncio"), + (AnalyticsAdminServiceClient, "rest"), +]) +def test_analytics_admin_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 == ( + 'analyticsadmin.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://analyticsadmin.googleapis.com' + ) + + +def test_analytics_admin_service_client_get_transport_class(): + transport = AnalyticsAdminServiceClient.get_transport_class() + available_transports = [ + transports.AnalyticsAdminServiceGrpcTransport, + transports.AnalyticsAdminServiceRestTransport, + ] + assert transport in available_transports + + transport = AnalyticsAdminServiceClient.get_transport_class("grpc") + assert transport == transports.AnalyticsAdminServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc"), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest"), +]) +@mock.patch.object(AnalyticsAdminServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceAsyncClient)) +def test_analytics_admin_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(AnalyticsAdminServiceClient, '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(AnalyticsAdminServiceClient, '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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc", "true"), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc", "false"), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest", "true"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AnalyticsAdminServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_analytics_admin_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", [ + AnalyticsAdminServiceClient, AnalyticsAdminServiceAsyncClient +]) +@mock.patch.object(AnalyticsAdminServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AnalyticsAdminServiceAsyncClient)) +def test_analytics_admin_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", [ + AnalyticsAdminServiceClient, AnalyticsAdminServiceAsyncClient +]) +@mock.patch.object(AnalyticsAdminServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceClient)) +@mock.patch.object(AnalyticsAdminServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AnalyticsAdminServiceAsyncClient)) +def test_analytics_admin_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AnalyticsAdminServiceClient._DEFAULT_UNIVERSE + default_endpoint = AnalyticsAdminServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AnalyticsAdminServiceClient._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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc"), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest"), +]) +def test_analytics_admin_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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc", grpc_helpers), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceRestTransport, "rest", None), +]) +def test_analytics_admin_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_analytics_admin_service_client_client_options_from_dict(): + with mock.patch('google.analytics.admin_v1beta.services.analytics_admin_service.transports.AnalyticsAdminServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AnalyticsAdminServiceClient( + 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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport, "grpc", grpc_helpers), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_analytics_admin_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( + "analyticsadmin.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/analytics.edit', + 'https://www.googleapis.com/auth/analytics.readonly', +), + scopes=None, + default_host="analyticsadmin.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAccountRequest, + dict, +]) +def test_get_account(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + ) + response = client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + + +def test_get_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccountRequest() + + +def test_get_account_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetAccountRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccountRequest( + name='name_value', + ) + +def test_get_account_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account] = mock_rpc + request = {} + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_account_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 = AnalyticsAdminServiceAsyncClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + )) + response = await client.get_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetAccountRequest() + +@pytest.mark.asyncio +async def test_get_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_account] = mock_object + + request = {} + await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_account_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetAccountRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + )) + response = await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + + +@pytest.mark.asyncio +async def test_get_account_async_from_dict(): + await test_get_account_async(request_type=dict) + + +def test_get_account_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = resources.Account() + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_account_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account()) + await client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_account_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_account( + 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_account_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_account( + analytics_admin.GetAccountRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_account_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_account( + 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_account_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_account( + analytics_admin.GetAccountRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccountsRequest, + dict, +]) +def test_list_accounts(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAccountsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_accounts_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_accounts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountsRequest() + + +def test_list_accounts_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccountsRequest( + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_accounts(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountsRequest( + page_token='page_token_value', + ) + +def test_list_accounts_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_accounts] = mock_rpc + request = {} + client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accounts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_accounts_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 = AnalyticsAdminServiceAsyncClient( + 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_accounts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountsRequest() + +@pytest.mark.asyncio +async def test_list_accounts_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_accounts in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_accounts] = mock_object + + request = {} + await client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_accounts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_accounts_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListAccountsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_accounts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccountsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccountsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_accounts_async_from_dict(): + await test_list_accounts_async(request_type=dict) + + +def test_list_accounts_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_accounts(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Account) + for i in results) +def test_list_accounts_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_accounts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + RuntimeError, + ) + pages = list(client.list_accounts(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_accounts_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_accounts(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, resources.Account) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_accounts_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_accounts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + 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_accounts(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", [ + analytics_admin.DeleteAccountRequest, + dict, +]) +def test_delete_account(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAccountRequest() + + +def test_delete_account_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteAccountRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAccountRequest( + name='name_value', + ) + +def test_delete_account_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_account] = mock_rpc + request = {} + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_account_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 = AnalyticsAdminServiceAsyncClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteAccountRequest() + +@pytest.mark.asyncio +async def test_delete_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_account] = mock_object + + request = {} + await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_account_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteAccountRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteAccountRequest() + 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_account_async_from_dict(): + await test_delete_account_async(request_type=dict) + + +def test_delete_account_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = None + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_account_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteAccountRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_account_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__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_account( + 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_account_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_account( + analytics_admin.DeleteAccountRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_account_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account), + '__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_account( + 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_account_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_account( + analytics_admin.DeleteAccountRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAccountRequest, + dict, +]) +def test_update_account(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + ) + response = client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + + +def test_update_account_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAccountRequest() + + +def test_update_account_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateAccountRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_account(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAccountRequest( + ) + +def test_update_account_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + request = {} + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_account_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 = AnalyticsAdminServiceAsyncClient( + 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + )) + response = await client.update_account() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateAccountRequest() + +@pytest.mark.asyncio +async def test_update_account_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_account in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_account] = mock_object + + request = {} + await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_account_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateAccountRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_value', + )) + response = await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateAccountRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + + +@pytest.mark.asyncio +async def test_update_account_async_from_dict(): + await test_update_account_async(request_type=dict) + + +def test_update_account_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAccountRequest() + + request.account.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = resources.Account() + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'account.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_account_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateAccountRequest() + + request.account.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account()) + await client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'account.name=name_value', + ) in kw['metadata'] + + +def test_update_account_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_account( + account=resources.Account(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].account + mock_val = resources.Account(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_account_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_account( + analytics_admin.UpdateAccountRequest(), + account=resources.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_account_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Account() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Account()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_account( + account=resources.Account(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].account + mock_val = resources.Account(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_account_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_account( + analytics_admin.UpdateAccountRequest(), + account=resources.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ProvisionAccountTicketRequest, + dict, +]) +def test_provision_account_ticket(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_account_ticket), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ProvisionAccountTicketResponse( + account_ticket_id='account_ticket_id_value', + ) + response = client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ProvisionAccountTicketRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionAccountTicketResponse) + assert response.account_ticket_id == 'account_ticket_id_value' + + +def test_provision_account_ticket_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_account_ticket), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.provision_account_ticket() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionAccountTicketRequest() + + +def test_provision_account_ticket_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ProvisionAccountTicketRequest( + redirect_uri='redirect_uri_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_account_ticket), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.provision_account_ticket(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionAccountTicketRequest( + redirect_uri='redirect_uri_value', + ) + +def test_provision_account_ticket_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.provision_account_ticket in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.provision_account_ticket] = mock_rpc + request = {} + client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provision_account_ticket(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_provision_account_ticket_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 = AnalyticsAdminServiceAsyncClient( + 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.provision_account_ticket), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ProvisionAccountTicketResponse( + account_ticket_id='account_ticket_id_value', + )) + response = await client.provision_account_ticket() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ProvisionAccountTicketRequest() + +@pytest.mark.asyncio +async def test_provision_account_ticket_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.provision_account_ticket in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.provision_account_ticket] = mock_object + + request = {} + await client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.provision_account_ticket(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_provision_account_ticket_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ProvisionAccountTicketRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.provision_account_ticket), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ProvisionAccountTicketResponse( + account_ticket_id='account_ticket_id_value', + )) + response = await client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ProvisionAccountTicketRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionAccountTicketResponse) + assert response.account_ticket_id == 'account_ticket_id_value' + + +@pytest.mark.asyncio +async def test_provision_account_ticket_async_from_dict(): + await test_provision_account_ticket_async(request_type=dict) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccountSummariesRequest, + dict, +]) +def test_list_account_summaries(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account_summaries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListAccountSummariesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccountSummariesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountSummariesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_account_summaries_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_account_summaries), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_account_summaries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountSummariesRequest() + + +def test_list_account_summaries_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccountSummariesRequest( + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_summaries), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_account_summaries(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountSummariesRequest( + page_token='page_token_value', + ) + +def test_list_account_summaries_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_account_summaries in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_account_summaries] = mock_rpc + request = {} + client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_summaries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_account_summaries_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 = AnalyticsAdminServiceAsyncClient( + 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_account_summaries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccountSummariesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_account_summaries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListAccountSummariesRequest() + +@pytest.mark.asyncio +async def test_list_account_summaries_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_account_summaries in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_account_summaries] = mock_object + + request = {} + await client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_account_summaries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_account_summaries_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListAccountSummariesRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_account_summaries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListAccountSummariesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListAccountSummariesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountSummariesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_account_summaries_async_from_dict(): + await test_list_account_summaries_async(request_type=dict) + + +def test_list_account_summaries_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_account_summaries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_account_summaries(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AccountSummary) + for i in results) +def test_list_account_summaries_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_account_summaries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + RuntimeError, + ) + pages = list(client.list_account_summaries(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_account_summaries_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_summaries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_account_summaries(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, resources.AccountSummary) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_account_summaries_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_summaries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + 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_account_summaries(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", [ + analytics_admin.GetPropertyRequest, + dict, +]) +def test_get_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + ) + response = client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetPropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +def test_get_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetPropertyRequest() + + +def test_get_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetPropertyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetPropertyRequest( + name='name_value', + ) + +def test_get_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_property] = mock_rpc + request = {} + client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_property_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 = AnalyticsAdminServiceAsyncClient( + 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.get_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetPropertyRequest() + +@pytest.mark.asyncio +async def test_get_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_property] = mock_object + + request = {} + await client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetPropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetPropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +@pytest.mark.asyncio +async def test_get_property_async_from_dict(): + await test_get_property_async(request_type=dict) + + +def test_get_property_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetPropertyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + call.return_value = resources.Property() + client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_property_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetPropertyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + await client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_property_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_property( + 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_property_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_property( + analytics_admin.GetPropertyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_property_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_property( + 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_property_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_property( + analytics_admin.GetPropertyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListPropertiesRequest, + dict, +]) +def test_list_properties(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListPropertiesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListPropertiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPropertiesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_properties_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_properties), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_properties() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListPropertiesRequest() + + +def test_list_properties_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListPropertiesRequest( + filter='filter_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_properties), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_properties(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListPropertiesRequest( + filter='filter_value', + page_token='page_token_value', + ) + +def test_list_properties_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_properties in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_properties] = mock_rpc + request = {} + client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_properties(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_properties_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 = AnalyticsAdminServiceAsyncClient( + 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_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListPropertiesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_properties() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListPropertiesRequest() + +@pytest.mark.asyncio +async def test_list_properties_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_properties in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_properties] = mock_object + + request = {} + await client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_properties(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_properties_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListPropertiesRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_properties), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListPropertiesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListPropertiesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPropertiesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_properties_async_from_dict(): + await test_list_properties_async(request_type=dict) + + +def test_list_properties_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_properties), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + pager = client.list_properties(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Property) + for i in results) +def test_list_properties_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_properties), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + RuntimeError, + ) + pages = list(client.list_properties(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_properties_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_properties), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_properties(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, resources.Property) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_properties_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_properties), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + 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_properties(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", [ + analytics_admin.CreatePropertyRequest, + dict, +]) +def test_create_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + ) + response = client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreatePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +def test_create_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreatePropertyRequest() + + +def test_create_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreatePropertyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreatePropertyRequest( + ) + +def test_create_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_property] = mock_rpc + request = {} + client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_property_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 = AnalyticsAdminServiceAsyncClient( + 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.create_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreatePropertyRequest() + +@pytest.mark.asyncio +async def test_create_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_property] = mock_object + + request = {} + await client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreatePropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreatePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +@pytest.mark.asyncio +async def test_create_property_async_from_dict(): + await test_create_property_async(request_type=dict) + + +def test_create_property_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_property( + property=resources.Property(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].property + mock_val = resources.Property(name='name_value') + assert arg == mock_val + + +def test_create_property_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_property( + analytics_admin.CreatePropertyRequest(), + property=resources.Property(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_property_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_property( + property=resources.Property(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].property + mock_val = resources.Property(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_property_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_property( + analytics_admin.CreatePropertyRequest(), + property=resources.Property(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeletePropertyRequest, + dict, +]) +def test_delete_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + ) + response = client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeletePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +def test_delete_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeletePropertyRequest() + + +def test_delete_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeletePropertyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeletePropertyRequest( + name='name_value', + ) + +def test_delete_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_property] = mock_rpc + request = {} + client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_property_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 = AnalyticsAdminServiceAsyncClient( + 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.delete_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeletePropertyRequest() + +@pytest.mark.asyncio +async def test_delete_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_property] = mock_object + + request = {} + await client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeletePropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeletePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +@pytest.mark.asyncio +async def test_delete_property_async_from_dict(): + await test_delete_property_async(request_type=dict) + + +def test_delete_property_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeletePropertyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + call.return_value = resources.Property() + client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_property_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeletePropertyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + await client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_property_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_property( + 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_property_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_property( + analytics_admin.DeletePropertyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_property_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_property( + 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_property_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_property( + analytics_admin.DeletePropertyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdatePropertyRequest, + dict, +]) +def test_update_property(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + ) + response = client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdatePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +def test_update_property_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdatePropertyRequest() + + +def test_update_property_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdatePropertyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_property(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdatePropertyRequest( + ) + +def test_update_property_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_property] = mock_rpc + request = {} + client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_property_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 = AnalyticsAdminServiceAsyncClient( + 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.update_property() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdatePropertyRequest() + +@pytest.mark.asyncio +async def test_update_property_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_property in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_property] = mock_object + + request = {} + await client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_property_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdatePropertyRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_value', + )) + response = await client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdatePropertyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + + +@pytest.mark.asyncio +async def test_update_property_async_from_dict(): + await test_update_property_async(request_type=dict) + + +def test_update_property_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdatePropertyRequest() + + request.property.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + call.return_value = resources.Property() + client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'property.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_property_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdatePropertyRequest() + + request.property.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + await client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'property.name=name_value', + ) in kw['metadata'] + + +def test_update_property_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_property( + property=resources.Property(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].property + mock_val = resources.Property(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_property_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_property( + analytics_admin.UpdatePropertyRequest(), + property=resources.Property(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_property_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_property), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Property() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Property()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_property( + property=resources.Property(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].property + mock_val = resources.Property(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_property_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_property( + analytics_admin.UpdatePropertyRequest(), + property=resources.Property(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateFirebaseLinkRequest, + dict, +]) +def test_create_firebase_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.FirebaseLink( + name='name_value', + project='project_value', + ) + response = client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateFirebaseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.FirebaseLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + + +def test_create_firebase_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_firebase_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_firebase_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateFirebaseLinkRequest() + + +def test_create_firebase_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateFirebaseLinkRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_firebase_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateFirebaseLinkRequest( + parent='parent_value', + ) + +def test_create_firebase_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_firebase_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_firebase_link] = mock_rpc + request = {} + client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_firebase_link_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 = AnalyticsAdminServiceAsyncClient( + 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.FirebaseLink( + name='name_value', + project='project_value', + )) + response = await client.create_firebase_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateFirebaseLinkRequest() + +@pytest.mark.asyncio +async def test_create_firebase_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_firebase_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_firebase_link] = mock_object + + request = {} + await client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_firebase_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateFirebaseLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.FirebaseLink( + name='name_value', + project='project_value', + )) + response = await client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateFirebaseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.FirebaseLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + + +@pytest.mark.asyncio +async def test_create_firebase_link_async_from_dict(): + await test_create_firebase_link_async(request_type=dict) + + +def test_create_firebase_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateFirebaseLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + call.return_value = resources.FirebaseLink() + client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateFirebaseLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.FirebaseLink()) + await client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.FirebaseLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_firebase_link( + parent='parent_value', + firebase_link=resources.FirebaseLink(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].firebase_link + mock_val = resources.FirebaseLink(name='name_value') + assert arg == mock_val + + +def test_create_firebase_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_firebase_link( + analytics_admin.CreateFirebaseLinkRequest(), + parent='parent_value', + firebase_link=resources.FirebaseLink(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_firebase_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.FirebaseLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.FirebaseLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_firebase_link( + parent='parent_value', + firebase_link=resources.FirebaseLink(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].firebase_link + mock_val = resources.FirebaseLink(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_firebase_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_firebase_link( + analytics_admin.CreateFirebaseLinkRequest(), + parent='parent_value', + firebase_link=resources.FirebaseLink(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteFirebaseLinkRequest, + dict, +]) +def test_delete_firebase_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteFirebaseLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_firebase_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_firebase_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_firebase_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteFirebaseLinkRequest() + + +def test_delete_firebase_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteFirebaseLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_firebase_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteFirebaseLinkRequest( + name='name_value', + ) + +def test_delete_firebase_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_firebase_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_firebase_link] = mock_rpc + request = {} + client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_firebase_link_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 = AnalyticsAdminServiceAsyncClient( + 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_firebase_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteFirebaseLinkRequest() + +@pytest.mark.asyncio +async def test_delete_firebase_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_firebase_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_firebase_link] = mock_object + + request = {} + await client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_firebase_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteFirebaseLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteFirebaseLinkRequest() + 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_firebase_link_async_from_dict(): + await test_delete_firebase_link_async(request_type=dict) + + +def test_delete_firebase_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteFirebaseLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__call__') as call: + call.return_value = None + client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteFirebaseLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__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_firebase_link( + 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_firebase_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_firebase_link( + analytics_admin.DeleteFirebaseLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_firebase_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_firebase_link), + '__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_firebase_link( + 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_firebase_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_firebase_link( + analytics_admin.DeleteFirebaseLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListFirebaseLinksRequest, + dict, +]) +def test_list_firebase_links(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListFirebaseLinksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListFirebaseLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirebaseLinksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_firebase_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_firebase_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_firebase_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListFirebaseLinksRequest() + + +def test_list_firebase_links_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListFirebaseLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_firebase_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListFirebaseLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_firebase_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_firebase_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_firebase_links] = mock_rpc + request = {} + client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_firebase_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_firebase_links_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 = AnalyticsAdminServiceAsyncClient( + 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_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListFirebaseLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_firebase_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListFirebaseLinksRequest() + +@pytest.mark.asyncio +async def test_list_firebase_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_firebase_links in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_firebase_links] = mock_object + + request = {} + await client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_firebase_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_firebase_links_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListFirebaseLinksRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListFirebaseLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListFirebaseLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirebaseLinksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_firebase_links_async_from_dict(): + await test_list_firebase_links_async(request_type=dict) + + +def test_list_firebase_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListFirebaseLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + call.return_value = analytics_admin.ListFirebaseLinksResponse() + client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListFirebaseLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListFirebaseLinksResponse()) + await client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_firebase_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListFirebaseLinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_firebase_links( + 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_firebase_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_firebase_links( + analytics_admin.ListFirebaseLinksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_firebase_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListFirebaseLinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListFirebaseLinksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_firebase_links( + 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_firebase_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_firebase_links( + analytics_admin.ListFirebaseLinksRequest(), + parent='parent_value', + ) + + +def test_list_firebase_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_firebase_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_firebase_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.FirebaseLink) + for i in results) +def test_list_firebase_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_firebase_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_firebase_links(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_firebase_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_firebase_links(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, resources.FirebaseLink) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_firebase_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_firebase_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + 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_firebase_links(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", [ + analytics_admin.CreateGoogleAdsLinkRequest, + dict, +]) +def test_create_google_ads_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + ) + response = client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + + +def test_create_google_ads_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateGoogleAdsLinkRequest() + + +def test_create_google_ads_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateGoogleAdsLinkRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_google_ads_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateGoogleAdsLinkRequest( + parent='parent_value', + ) + +def test_create_google_ads_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_google_ads_link] = mock_rpc + request = {} + client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_google_ads_link_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 = AnalyticsAdminServiceAsyncClient( + 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + )) + response = await client.create_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateGoogleAdsLinkRequest() + +@pytest.mark.asyncio +async def test_create_google_ads_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_google_ads_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_google_ads_link] = mock_object + + request = {} + await client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_google_ads_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateGoogleAdsLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + )) + response = await client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + + +@pytest.mark.asyncio +async def test_create_google_ads_link_async_from_dict(): + await test_create_google_ads_link_async(request_type=dict) + + +def test_create_google_ads_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateGoogleAdsLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + call.return_value = resources.GoogleAdsLink() + client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateGoogleAdsLinkRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink()) + await client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_google_ads_link( + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(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].google_ads_link + mock_val = resources.GoogleAdsLink(name='name_value') + assert arg == mock_val + + +def test_create_google_ads_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link( + analytics_admin.CreateGoogleAdsLinkRequest(), + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_google_ads_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_google_ads_link( + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(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].google_ads_link + mock_val = resources.GoogleAdsLink(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_google_ads_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_ads_link( + analytics_admin.CreateGoogleAdsLinkRequest(), + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateGoogleAdsLinkRequest, + dict, +]) +def test_update_google_ads_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + ) + response = client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + + +def test_update_google_ads_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateGoogleAdsLinkRequest() + + +def test_update_google_ads_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateGoogleAdsLinkRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_google_ads_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateGoogleAdsLinkRequest( + ) + +def test_update_google_ads_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_google_ads_link] = mock_rpc + request = {} + client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_google_ads_link_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 = AnalyticsAdminServiceAsyncClient( + 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + )) + response = await client.update_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateGoogleAdsLinkRequest() + +@pytest.mark.asyncio +async def test_update_google_ads_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_google_ads_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_google_ads_link] = mock_object + + request = {} + await client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_google_ads_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateGoogleAdsLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_value', + )) + response = await client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + + +@pytest.mark.asyncio +async def test_update_google_ads_link_async_from_dict(): + await test_update_google_ads_link_async(request_type=dict) + + +def test_update_google_ads_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateGoogleAdsLinkRequest() + + request.google_ads_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + call.return_value = resources.GoogleAdsLink() + client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_ads_link.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_google_ads_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateGoogleAdsLinkRequest() + + request.google_ads_link.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink()) + await client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'google_ads_link.name=name_value', + ) in kw['metadata'] + + +def test_update_google_ads_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_google_ads_link( + google_ads_link=resources.GoogleAdsLink(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].google_ads_link + mock_val = resources.GoogleAdsLink(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_google_ads_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link( + analytics_admin.UpdateGoogleAdsLinkRequest(), + google_ads_link=resources.GoogleAdsLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_google_ads_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.GoogleAdsLink() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.GoogleAdsLink()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_google_ads_link( + google_ads_link=resources.GoogleAdsLink(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].google_ads_link + mock_val = resources.GoogleAdsLink(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_google_ads_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_ads_link( + analytics_admin.UpdateGoogleAdsLinkRequest(), + google_ads_link=resources.GoogleAdsLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteGoogleAdsLinkRequest, + dict, +]) +def test_delete_google_ads_link(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteGoogleAdsLinkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_google_ads_link_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteGoogleAdsLinkRequest() + + +def test_delete_google_ads_link_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteGoogleAdsLinkRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_google_ads_link(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteGoogleAdsLinkRequest( + name='name_value', + ) + +def test_delete_google_ads_link_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_google_ads_link] = mock_rpc + request = {} + client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_google_ads_link_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 = AnalyticsAdminServiceAsyncClient( + 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_google_ads_link() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteGoogleAdsLinkRequest() + +@pytest.mark.asyncio +async def test_delete_google_ads_link_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_google_ads_link in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_google_ads_link] = mock_object + + request = {} + await client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_google_ads_link_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteGoogleAdsLinkRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_link), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteGoogleAdsLinkRequest() + 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_google_ads_link_async_from_dict(): + await test_delete_google_ads_link_async(request_type=dict) + + +def test_delete_google_ads_link_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteGoogleAdsLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__call__') as call: + call.return_value = None + client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_link_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteGoogleAdsLinkRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_link_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__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_google_ads_link( + 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_google_ads_link_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_link( + analytics_admin.DeleteGoogleAdsLinkRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_google_ads_link_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_google_ads_link), + '__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_google_ads_link( + 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_google_ads_link_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_ads_link( + analytics_admin.DeleteGoogleAdsLinkRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListGoogleAdsLinksRequest, + dict, +]) +def test_list_google_ads_links(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListGoogleAdsLinksResponse( + next_page_token='next_page_token_value', + ) + response = client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListGoogleAdsLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleAdsLinksPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_google_ads_links_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_google_ads_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListGoogleAdsLinksRequest() + + +def test_list_google_ads_links_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListGoogleAdsLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_google_ads_links(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListGoogleAdsLinksRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_google_ads_links_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_google_ads_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_google_ads_links] = mock_rpc + request = {} + client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_google_ads_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_google_ads_links_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 = AnalyticsAdminServiceAsyncClient( + 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_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListGoogleAdsLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_google_ads_links() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListGoogleAdsLinksRequest() + +@pytest.mark.asyncio +async def test_list_google_ads_links_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_google_ads_links in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_google_ads_links] = mock_object + + request = {} + await client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_google_ads_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_google_ads_links_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListGoogleAdsLinksRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListGoogleAdsLinksResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListGoogleAdsLinksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleAdsLinksAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_google_ads_links_async_from_dict(): + await test_list_google_ads_links_async(request_type=dict) + + +def test_list_google_ads_links_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListGoogleAdsLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + call.return_value = analytics_admin.ListGoogleAdsLinksResponse() + client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_links_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListGoogleAdsLinksRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListGoogleAdsLinksResponse()) + await client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_google_ads_links_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListGoogleAdsLinksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_google_ads_links( + 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_google_ads_links_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_google_ads_links( + analytics_admin.ListGoogleAdsLinksRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_google_ads_links_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListGoogleAdsLinksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListGoogleAdsLinksResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_google_ads_links( + 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_google_ads_links_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_google_ads_links( + analytics_admin.ListGoogleAdsLinksRequest(), + parent='parent_value', + ) + + +def test_list_google_ads_links_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_google_ads_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_google_ads_links(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.GoogleAdsLink) + for i in results) +def test_list_google_ads_links_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_google_ads_links), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + RuntimeError, + ) + pages = list(client.list_google_ads_links(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_google_ads_links_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_google_ads_links(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, resources.GoogleAdsLink) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_google_ads_links_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_google_ads_links), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + 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_google_ads_links(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", [ + analytics_admin.GetDataSharingSettingsRequest, + dict, +]) +def test_get_data_sharing_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataSharingSettings( + name='name_value', + sharing_with_google_support_enabled=True, + sharing_with_google_assigned_sales_enabled=True, + sharing_with_google_any_sales_enabled=True, + sharing_with_google_products_enabled=True, + sharing_with_others_enabled=True, + ) + response = client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataSharingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataSharingSettings) + assert response.name == 'name_value' + assert response.sharing_with_google_support_enabled is True + assert response.sharing_with_google_assigned_sales_enabled is True + assert response.sharing_with_google_any_sales_enabled is True + assert response.sharing_with_google_products_enabled is True + assert response.sharing_with_others_enabled is True + + +def test_get_data_sharing_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_sharing_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataSharingSettingsRequest() + + +def test_get_data_sharing_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetDataSharingSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_sharing_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataSharingSettingsRequest( + name='name_value', + ) + +def test_get_data_sharing_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_sharing_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_sharing_settings] = mock_rpc + request = {} + client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_sharing_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataSharingSettings( + name='name_value', + sharing_with_google_support_enabled=True, + sharing_with_google_assigned_sales_enabled=True, + sharing_with_google_any_sales_enabled=True, + sharing_with_google_products_enabled=True, + sharing_with_others_enabled=True, + )) + response = await client.get_data_sharing_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataSharingSettingsRequest() + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_data_sharing_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_data_sharing_settings] = mock_object + + request = {} + await client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_data_sharing_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetDataSharingSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataSharingSettings( + name='name_value', + sharing_with_google_support_enabled=True, + sharing_with_google_assigned_sales_enabled=True, + sharing_with_google_any_sales_enabled=True, + sharing_with_google_products_enabled=True, + sharing_with_others_enabled=True, + )) + response = await client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataSharingSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataSharingSettings) + assert response.name == 'name_value' + assert response.sharing_with_google_support_enabled is True + assert response.sharing_with_google_assigned_sales_enabled is True + assert response.sharing_with_google_any_sales_enabled is True + assert response.sharing_with_google_products_enabled is True + assert response.sharing_with_others_enabled is True + + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_async_from_dict(): + await test_get_data_sharing_settings_async(request_type=dict) + + +def test_get_data_sharing_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataSharingSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + call.return_value = resources.DataSharingSettings() + client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataSharingSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataSharingSettings()) + await client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_data_sharing_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataSharingSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_sharing_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_data_sharing_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_sharing_settings( + analytics_admin.GetDataSharingSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_sharing_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataSharingSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataSharingSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_sharing_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_data_sharing_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_sharing_settings( + analytics_admin.GetDataSharingSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetMeasurementProtocolSecretRequest, + dict, +]) +def test_get_measurement_protocol_secret(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + ) + response = client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +def test_get_measurement_protocol_secret_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetMeasurementProtocolSecretRequest() + + +def test_get_measurement_protocol_secret_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetMeasurementProtocolSecretRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_measurement_protocol_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetMeasurementProtocolSecretRequest( + name='name_value', + ) + +def test_get_measurement_protocol_secret_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_measurement_protocol_secret] = mock_rpc + request = {} + client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.get_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetMeasurementProtocolSecretRequest() + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_measurement_protocol_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_measurement_protocol_secret] = mock_object + + request = {} + await client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_async_from_dict(): + await test_get_measurement_protocol_secret_async(request_type=dict) + + +def test_get_measurement_protocol_secret_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetMeasurementProtocolSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + call.return_value = resources.MeasurementProtocolSecret() + client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetMeasurementProtocolSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + await client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_measurement_protocol_secret( + 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_measurement_protocol_secret_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret( + analytics_admin.GetMeasurementProtocolSecretRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_measurement_protocol_secret_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_measurement_protocol_secret( + 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_measurement_protocol_secret_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secret( + analytics_admin.GetMeasurementProtocolSecretRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListMeasurementProtocolSecretsRequest, + dict, +]) +def test_list_measurement_protocol_secrets(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeasurementProtocolSecretsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_measurement_protocol_secrets_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secrets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_measurement_protocol_secrets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListMeasurementProtocolSecretsRequest() + + +def test_list_measurement_protocol_secrets_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListMeasurementProtocolSecretsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_measurement_protocol_secrets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListMeasurementProtocolSecretsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_measurement_protocol_secrets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_measurement_protocol_secrets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_measurement_protocol_secrets] = mock_rpc + request = {} + client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_measurement_protocol_secrets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListMeasurementProtocolSecretsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_measurement_protocol_secrets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListMeasurementProtocolSecretsRequest() + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_measurement_protocol_secrets in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_measurement_protocol_secrets] = mock_object + + request = {} + await client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_measurement_protocol_secrets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListMeasurementProtocolSecretsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListMeasurementProtocolSecretsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeasurementProtocolSecretsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_async_from_dict(): + await test_list_measurement_protocol_secrets_async(request_type=dict) + + +def test_list_measurement_protocol_secrets_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + call.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secrets_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListMeasurementProtocolSecretsResponse()) + await client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secrets_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_measurement_protocol_secrets( + 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_measurement_protocol_secrets_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secrets( + analytics_admin.ListMeasurementProtocolSecretsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListMeasurementProtocolSecretsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_measurement_protocol_secrets( + 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_measurement_protocol_secrets_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secrets( + analytics_admin.ListMeasurementProtocolSecretsRequest(), + parent='parent_value', + ) + + +def test_list_measurement_protocol_secrets_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secrets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_measurement_protocol_secrets(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.MeasurementProtocolSecret) + for i in results) +def test_list_measurement_protocol_secrets_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secrets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + RuntimeError, + ) + pages = list(client.list_measurement_protocol_secrets(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_measurement_protocol_secrets_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_measurement_protocol_secrets(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, resources.MeasurementProtocolSecret) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_measurement_protocol_secrets_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_measurement_protocol_secrets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + 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_measurement_protocol_secrets(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", [ + analytics_admin.CreateMeasurementProtocolSecretRequest, + dict, +]) +def test_create_measurement_protocol_secret(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + ) + response = client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +def test_create_measurement_protocol_secret_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateMeasurementProtocolSecretRequest() + + +def test_create_measurement_protocol_secret_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateMeasurementProtocolSecretRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_measurement_protocol_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateMeasurementProtocolSecretRequest( + parent='parent_value', + ) + +def test_create_measurement_protocol_secret_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_measurement_protocol_secret] = mock_rpc + request = {} + client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.create_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateMeasurementProtocolSecretRequest() + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_measurement_protocol_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_measurement_protocol_secret] = mock_object + + request = {} + await client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_async_from_dict(): + await test_create_measurement_protocol_secret_async(request_type=dict) + + +def test_create_measurement_protocol_secret_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + call.return_value = resources.MeasurementProtocolSecret() + client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + await client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_measurement_protocol_secret( + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(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].measurement_protocol_secret + mock_val = resources.MeasurementProtocolSecret(name='name_value') + assert arg == mock_val + + +def test_create_measurement_protocol_secret_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret( + analytics_admin.CreateMeasurementProtocolSecretRequest(), + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_measurement_protocol_secret( + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(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].measurement_protocol_secret + mock_val = resources.MeasurementProtocolSecret(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_measurement_protocol_secret_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secret( + analytics_admin.CreateMeasurementProtocolSecretRequest(), + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteMeasurementProtocolSecretRequest, + dict, +]) +def test_delete_measurement_protocol_secret(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_measurement_protocol_secret_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteMeasurementProtocolSecretRequest() + + +def test_delete_measurement_protocol_secret_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteMeasurementProtocolSecretRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_measurement_protocol_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteMeasurementProtocolSecretRequest( + name='name_value', + ) + +def test_delete_measurement_protocol_secret_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_measurement_protocol_secret] = mock_rpc + request = {} + client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_measurement_protocol_secret_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteMeasurementProtocolSecretRequest() + +@pytest.mark.asyncio +async def test_delete_measurement_protocol_secret_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_measurement_protocol_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_measurement_protocol_secret] = mock_object + + request = {} + await client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_measurement_protocol_secret_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteMeasurementProtocolSecretRequest() + 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_measurement_protocol_secret_async_from_dict(): + await test_delete_measurement_protocol_secret_async(request_type=dict) + + +def test_delete_measurement_protocol_secret_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteMeasurementProtocolSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__call__') as call: + call.return_value = None + client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteMeasurementProtocolSecretRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_measurement_protocol_secret_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__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_measurement_protocol_secret( + 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_measurement_protocol_secret_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret( + analytics_admin.DeleteMeasurementProtocolSecretRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_measurement_protocol_secret_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_measurement_protocol_secret), + '__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_measurement_protocol_secret( + 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_measurement_protocol_secret_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secret( + analytics_admin.DeleteMeasurementProtocolSecretRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateMeasurementProtocolSecretRequest, + dict, +]) +def test_update_measurement_protocol_secret(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + ) + response = client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +def test_update_measurement_protocol_secret_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateMeasurementProtocolSecretRequest() + + +def test_update_measurement_protocol_secret_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateMeasurementProtocolSecretRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_measurement_protocol_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateMeasurementProtocolSecretRequest( + ) + +def test_update_measurement_protocol_secret_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_measurement_protocol_secret] = mock_rpc + request = {} + client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_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 = AnalyticsAdminServiceAsyncClient( + 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.update_measurement_protocol_secret() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateMeasurementProtocolSecretRequest() + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_measurement_protocol_secret in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_measurement_protocol_secret] = mock_object + + request = {} + await client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_value', + )) + response = await client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_async_from_dict(): + await test_update_measurement_protocol_secret_async(request_type=dict) + + +def test_update_measurement_protocol_secret_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + + request.measurement_protocol_secret.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + call.return_value = resources.MeasurementProtocolSecret() + client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'measurement_protocol_secret.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + + request.measurement_protocol_secret.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + await client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'measurement_protocol_secret.name=name_value', + ) in kw['metadata'] + + +def test_update_measurement_protocol_secret_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_measurement_protocol_secret( + measurement_protocol_secret=resources.MeasurementProtocolSecret(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].measurement_protocol_secret + mock_val = resources.MeasurementProtocolSecret(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_measurement_protocol_secret_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_measurement_protocol_secret( + analytics_admin.UpdateMeasurementProtocolSecretRequest(), + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_measurement_protocol_secret_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_measurement_protocol_secret), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.MeasurementProtocolSecret() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.MeasurementProtocolSecret()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_measurement_protocol_secret( + measurement_protocol_secret=resources.MeasurementProtocolSecret(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].measurement_protocol_secret + mock_val = resources.MeasurementProtocolSecret(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_measurement_protocol_secret_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_measurement_protocol_secret( + analytics_admin.UpdateMeasurementProtocolSecretRequest(), + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.AcknowledgeUserDataCollectionRequest, + dict, +]) +def test_acknowledge_user_data_collection(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.AcknowledgeUserDataCollectionResponse( + ) + response = client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.AcknowledgeUserDataCollectionResponse) + + +def test_acknowledge_user_data_collection_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.acknowledge_user_data_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.AcknowledgeUserDataCollectionRequest() + + +def test_acknowledge_user_data_collection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.AcknowledgeUserDataCollectionRequest( + property='property_value', + acknowledgement='acknowledgement_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.acknowledge_user_data_collection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.AcknowledgeUserDataCollectionRequest( + property='property_value', + acknowledgement='acknowledgement_value', + ) + +def test_acknowledge_user_data_collection_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.acknowledge_user_data_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.acknowledge_user_data_collection] = mock_rpc + request = {} + client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.acknowledge_user_data_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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.acknowledge_user_data_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.AcknowledgeUserDataCollectionResponse( + )) + response = await client.acknowledge_user_data_collection() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.AcknowledgeUserDataCollectionRequest() + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.acknowledge_user_data_collection in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.acknowledge_user_data_collection] = mock_object + + request = {} + await client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.acknowledge_user_data_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.AcknowledgeUserDataCollectionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.AcknowledgeUserDataCollectionResponse( + )) + response = await client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.AcknowledgeUserDataCollectionResponse) + + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_async_from_dict(): + await test_acknowledge_user_data_collection_async(request_type=dict) + + +def test_acknowledge_user_data_collection_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + call.return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() + client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_acknowledge_user_data_collection_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + + request.property = 'property_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.acknowledge_user_data_collection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.AcknowledgeUserDataCollectionResponse()) + await client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'property=property_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.SearchChangeHistoryEventsRequest, + dict, +]) +def test_search_change_history_events(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.SearchChangeHistoryEventsResponse( + next_page_token='next_page_token_value', + ) + response = client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.SearchChangeHistoryEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchChangeHistoryEventsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_change_history_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_change_history_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.SearchChangeHistoryEventsRequest() + + +def test_search_change_history_events_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.SearchChangeHistoryEventsRequest( + account='account_value', + property='property_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.search_change_history_events(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.SearchChangeHistoryEventsRequest( + account='account_value', + property='property_value', + page_token='page_token_value', + ) + +def test_search_change_history_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_change_history_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_change_history_events] = mock_rpc + request = {} + client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_change_history_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_search_change_history_events_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.SearchChangeHistoryEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_change_history_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.SearchChangeHistoryEventsRequest() + +@pytest.mark.asyncio +async def test_search_change_history_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.search_change_history_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.search_change_history_events] = mock_object + + request = {} + await client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.search_change_history_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_search_change_history_events_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.SearchChangeHistoryEventsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.SearchChangeHistoryEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.SearchChangeHistoryEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchChangeHistoryEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_change_history_events_async_from_dict(): + await test_search_change_history_events_async(request_type=dict) + + +def test_search_change_history_events_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.SearchChangeHistoryEventsRequest() + + request.account = 'account_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + call.return_value = analytics_admin.SearchChangeHistoryEventsResponse() + client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'account=account_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_change_history_events_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.SearchChangeHistoryEventsRequest() + + request.account = 'account_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.SearchChangeHistoryEventsResponse()) + await client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'account=account_value', + ) in kw['metadata'] + + +def test_search_change_history_events_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('account', ''), + )), + ) + pager = client.search_change_history_events(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ChangeHistoryEvent) + for i in results) +def test_search_change_history_events_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.search_change_history_events(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_search_change_history_events_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_change_history_events(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.ChangeHistoryEvent) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_change_history_events_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_change_history_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_change_history_events(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateConversionEventRequest, + dict, +]) +def test_create_conversion_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + response = client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +def test_create_conversion_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateConversionEventRequest() + + +def test_create_conversion_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateConversionEventRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_conversion_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateConversionEventRequest( + parent='parent_value', + ) + +def test_create_conversion_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_conversion_event] = mock_rpc + request = {} + client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_conversion_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.create_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateConversionEventRequest() + +@pytest.mark.asyncio +async def test_create_conversion_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_conversion_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_conversion_event] = mock_object + + request = {} + await client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_conversion_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateConversionEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_create_conversion_event_async_from_dict(): + await test_create_conversion_event_async(request_type=dict) + + +def test_create_conversion_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateConversionEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + call.return_value = resources.ConversionEvent() + client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_conversion_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateConversionEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + await client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_conversion_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_conversion_event( + parent='parent_value', + conversion_event=resources.ConversionEvent(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].conversion_event + mock_val = resources.ConversionEvent(name='name_value') + assert arg == mock_val + + +def test_create_conversion_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event( + analytics_admin.CreateConversionEventRequest(), + parent='parent_value', + conversion_event=resources.ConversionEvent(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_conversion_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_conversion_event( + parent='parent_value', + conversion_event=resources.ConversionEvent(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].conversion_event + mock_val = resources.ConversionEvent(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_conversion_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_event( + analytics_admin.CreateConversionEventRequest(), + parent='parent_value', + conversion_event=resources.ConversionEvent(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateConversionEventRequest, + dict, +]) +def test_update_conversion_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + response = client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +def test_update_conversion_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateConversionEventRequest() + + +def test_update_conversion_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateConversionEventRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_conversion_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateConversionEventRequest( + ) + +def test_update_conversion_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_conversion_event] = mock_rpc + request = {} + client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_conversion_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.update_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateConversionEventRequest() + +@pytest.mark.asyncio +async def test_update_conversion_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_conversion_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_conversion_event] = mock_object + + request = {} + await client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_conversion_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateConversionEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_update_conversion_event_async_from_dict(): + await test_update_conversion_event_async(request_type=dict) + + +def test_update_conversion_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateConversionEventRequest() + + request.conversion_event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + call.return_value = resources.ConversionEvent() + client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'conversion_event.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_conversion_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateConversionEventRequest() + + request.conversion_event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + await client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'conversion_event.name=name_value', + ) in kw['metadata'] + + +def test_update_conversion_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_conversion_event( + conversion_event=resources.ConversionEvent(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].conversion_event + mock_val = resources.ConversionEvent(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_conversion_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event( + analytics_admin.UpdateConversionEventRequest(), + conversion_event=resources.ConversionEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_conversion_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_conversion_event( + conversion_event=resources.ConversionEvent(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].conversion_event + mock_val = resources.ConversionEvent(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_conversion_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_event( + analytics_admin.UpdateConversionEventRequest(), + conversion_event=resources.ConversionEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetConversionEventRequest, + dict, +]) +def test_get_conversion_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + response = client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +def test_get_conversion_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetConversionEventRequest() + + +def test_get_conversion_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetConversionEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_conversion_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetConversionEventRequest( + name='name_value', + ) + +def test_get_conversion_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_conversion_event] = mock_rpc + request = {} + client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_conversion_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.get_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetConversionEventRequest() + +@pytest.mark.asyncio +async def test_get_conversion_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_conversion_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_conversion_event] = mock_object + + request = {} + await client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_conversion_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetConversionEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + )) + response = await client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_get_conversion_event_async_from_dict(): + await test_get_conversion_event_async(request_type=dict) + + +def test_get_conversion_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetConversionEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + call.return_value = resources.ConversionEvent() + client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_conversion_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetConversionEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + await client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_conversion_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversion_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_conversion_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event( + analytics_admin.GetConversionEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_conversion_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConversionEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ConversionEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversion_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_conversion_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_event( + analytics_admin.GetConversionEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteConversionEventRequest, + dict, +]) +def test_delete_conversion_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteConversionEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversion_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConversionEventRequest() + + +def test_delete_conversion_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteConversionEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_conversion_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConversionEventRequest( + name='name_value', + ) + +def test_delete_conversion_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_conversion_event] = mock_rpc + request = {} + client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_conversion_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversion_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteConversionEventRequest() + +@pytest.mark.asyncio +async def test_delete_conversion_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_conversion_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_conversion_event] = mock_object + + request = {} + await client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_conversion_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteConversionEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteConversionEventRequest() + 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_conversion_event_async_from_dict(): + await test_delete_conversion_event_async(request_type=dict) + + +def test_delete_conversion_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteConversionEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__call__') as call: + call.return_value = None + client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_conversion_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteConversionEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_conversion_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__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_conversion_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_conversion_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_event( + analytics_admin.DeleteConversionEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_conversion_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversion_event), + '__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_conversion_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_conversion_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_event( + analytics_admin.DeleteConversionEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListConversionEventsRequest, + dict, +]) +def test_list_conversion_events(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListConversionEventsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListConversionEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversionEventsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_conversion_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_conversion_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_conversion_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListConversionEventsRequest() + + +def test_list_conversion_events_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListConversionEventsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_conversion_events(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListConversionEventsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_conversion_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_conversion_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_conversion_events] = mock_rpc + request = {} + client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conversion_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_conversion_events_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConversionEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversion_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListConversionEventsRequest() + +@pytest.mark.asyncio +async def test_list_conversion_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_conversion_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_conversion_events] = mock_object + + request = {} + await client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_conversion_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_conversion_events_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListConversionEventsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConversionEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListConversionEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversionEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_conversion_events_async_from_dict(): + await test_list_conversion_events_async(request_type=dict) + + +def test_list_conversion_events_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListConversionEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + call.return_value = analytics_admin.ListConversionEventsResponse() + client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_conversion_events_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListConversionEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConversionEventsResponse()) + await client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_conversion_events_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListConversionEventsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversion_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_conversion_events_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_conversion_events( + analytics_admin.ListConversionEventsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_conversion_events_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListConversionEventsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListConversionEventsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversion_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_conversion_events_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_conversion_events( + analytics_admin.ListConversionEventsRequest(), + parent='parent_value', + ) + + +def test_list_conversion_events_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_conversion_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_conversion_events(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ConversionEvent) + for i in results) +def test_list_conversion_events_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_conversion_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversion_events(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_conversion_events_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversion_events(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.ConversionEvent) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_conversion_events_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversion_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + 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_conversion_events(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateKeyEventRequest, + dict, +]) +def test_create_key_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + response = client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +def test_create_key_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateKeyEventRequest() + + +def test_create_key_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateKeyEventRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_key_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateKeyEventRequest( + parent='parent_value', + ) + +def test_create_key_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_key_event] = mock_rpc + request = {} + client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_key_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.create_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateKeyEventRequest() + +@pytest.mark.asyncio +async def test_create_key_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_key_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_key_event] = mock_object + + request = {} + await client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_key_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateKeyEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_create_key_event_async_from_dict(): + await test_create_key_event_async(request_type=dict) + + +def test_create_key_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateKeyEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + call.return_value = resources.KeyEvent() + client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_key_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateKeyEventRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + await client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_key_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_key_event( + parent='parent_value', + key_event=resources.KeyEvent(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].key_event + mock_val = resources.KeyEvent(name='name_value') + assert arg == mock_val + + +def test_create_key_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_event( + analytics_admin.CreateKeyEventRequest(), + parent='parent_value', + key_event=resources.KeyEvent(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_key_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_key_event( + parent='parent_value', + key_event=resources.KeyEvent(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].key_event + mock_val = resources.KeyEvent(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_key_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_event( + analytics_admin.CreateKeyEventRequest(), + parent='parent_value', + key_event=resources.KeyEvent(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateKeyEventRequest, + dict, +]) +def test_update_key_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + response = client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +def test_update_key_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateKeyEventRequest() + + +def test_update_key_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateKeyEventRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_key_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateKeyEventRequest( + ) + +def test_update_key_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_key_event] = mock_rpc + request = {} + client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_key_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.update_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateKeyEventRequest() + +@pytest.mark.asyncio +async def test_update_key_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_key_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_key_event] = mock_object + + request = {} + await client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_key_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateKeyEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_update_key_event_async_from_dict(): + await test_update_key_event_async(request_type=dict) + + +def test_update_key_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateKeyEventRequest() + + request.key_event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + call.return_value = resources.KeyEvent() + client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'key_event.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_key_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateKeyEventRequest() + + request.key_event.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + await client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'key_event.name=name_value', + ) in kw['metadata'] + + +def test_update_key_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_key_event( + key_event=resources.KeyEvent(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].key_event + mock_val = resources.KeyEvent(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_key_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_event( + analytics_admin.UpdateKeyEventRequest(), + key_event=resources.KeyEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_key_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_key_event( + key_event=resources.KeyEvent(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].key_event + mock_val = resources.KeyEvent(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_key_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_event( + analytics_admin.UpdateKeyEventRequest(), + key_event=resources.KeyEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetKeyEventRequest, + dict, +]) +def test_get_key_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + response = client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +def test_get_key_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetKeyEventRequest() + + +def test_get_key_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetKeyEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_key_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetKeyEventRequest( + name='name_value', + ) + +def test_get_key_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_key_event] = mock_rpc + request = {} + client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_key_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.get_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetKeyEventRequest() + +@pytest.mark.asyncio +async def test_get_key_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_key_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_key_event] = mock_object + + request = {} + await client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_key_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetKeyEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + )) + response = await client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + + +@pytest.mark.asyncio +async def test_get_key_event_async_from_dict(): + await test_get_key_event_async(request_type=dict) + + +def test_get_key_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetKeyEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + call.return_value = resources.KeyEvent() + client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_key_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetKeyEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + await client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_key_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_key_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_key_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_event( + analytics_admin.GetKeyEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_key_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyEvent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyEvent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_key_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_key_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_event( + analytics_admin.GetKeyEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteKeyEventRequest, + dict, +]) +def test_delete_key_event(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteKeyEventRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_key_event_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteKeyEventRequest() + + +def test_delete_key_event_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteKeyEventRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_key_event(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteKeyEventRequest( + name='name_value', + ) + +def test_delete_key_event_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_key_event] = mock_rpc + request = {} + client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_key_event_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_key_event() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteKeyEventRequest() + +@pytest.mark.asyncio +async def test_delete_key_event_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_key_event in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_key_event] = mock_object + + request = {} + await client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_key_event_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteKeyEventRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_event), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteKeyEventRequest() + 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_key_event_async_from_dict(): + await test_delete_key_event_async(request_type=dict) + + +def test_delete_key_event_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteKeyEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__call__') as call: + call.return_value = None + client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_key_event_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteKeyEventRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_key_event_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__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_key_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_key_event_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_event( + analytics_admin.DeleteKeyEventRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_key_event_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_key_event), + '__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_key_event( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_key_event_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_event( + analytics_admin.DeleteKeyEventRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListKeyEventsRequest, + dict, +]) +def test_list_key_events(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListKeyEventsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListKeyEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyEventsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_key_events_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_key_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_key_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListKeyEventsRequest() + + +def test_list_key_events_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListKeyEventsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_key_events(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListKeyEventsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_key_events_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_key_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_key_events] = mock_rpc + request = {} + client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_key_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_key_events_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + 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_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListKeyEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_key_events() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListKeyEventsRequest() + +@pytest.mark.asyncio +async def test_list_key_events_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_key_events in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_key_events] = mock_object + + request = {} + await client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_key_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_key_events_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListKeyEventsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListKeyEventsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListKeyEventsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyEventsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_key_events_async_from_dict(): + await test_list_key_events_async(request_type=dict) + + +def test_list_key_events_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListKeyEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + call.return_value = analytics_admin.ListKeyEventsResponse() + client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_key_events_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListKeyEventsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListKeyEventsResponse()) + await client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_key_events_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListKeyEventsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_key_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_key_events_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_key_events( + analytics_admin.ListKeyEventsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_key_events_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListKeyEventsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListKeyEventsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_key_events( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_key_events_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_key_events( + analytics_admin.ListKeyEventsRequest(), + parent='parent_value', + ) + + +def test_list_key_events_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_key_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_key_events(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.KeyEvent) + for i in results) +def test_list_key_events_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_key_events), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_key_events(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_key_events_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_key_events(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.KeyEvent) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_key_events_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_events), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + 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_key_events(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateCustomDimensionRequest, + dict, +]) +def test_create_custom_dimension(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + ) + response = client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +def test_create_custom_dimension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomDimensionRequest() + + +def test_create_custom_dimension_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateCustomDimensionRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_custom_dimension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomDimensionRequest( + parent='parent_value', + ) + +def test_create_custom_dimension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_custom_dimension] = mock_rpc + request = {} + client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_custom_dimension_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.create_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomDimensionRequest() + +@pytest.mark.asyncio +async def test_create_custom_dimension_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_custom_dimension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_custom_dimension] = mock_object + + request = {} + await client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_custom_dimension_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateCustomDimensionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +@pytest.mark.asyncio +async def test_create_custom_dimension_async_from_dict(): + await test_create_custom_dimension_async(request_type=dict) + + +def test_create_custom_dimension_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCustomDimensionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + call.return_value = resources.CustomDimension() + client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimension_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCustomDimensionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + await client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimension_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_custom_dimension( + parent='parent_value', + custom_dimension=resources.CustomDimension(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].custom_dimension + mock_val = resources.CustomDimension(name='name_value') + assert arg == mock_val + + +def test_create_custom_dimension_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension( + analytics_admin.CreateCustomDimensionRequest(), + parent='parent_value', + custom_dimension=resources.CustomDimension(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_custom_dimension_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_custom_dimension( + parent='parent_value', + custom_dimension=resources.CustomDimension(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].custom_dimension + mock_val = resources.CustomDimension(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_custom_dimension_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_dimension( + analytics_admin.CreateCustomDimensionRequest(), + parent='parent_value', + custom_dimension=resources.CustomDimension(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateCustomDimensionRequest, + dict, +]) +def test_update_custom_dimension(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + ) + response = client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +def test_update_custom_dimension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomDimensionRequest() + + +def test_update_custom_dimension_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateCustomDimensionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_custom_dimension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomDimensionRequest( + ) + +def test_update_custom_dimension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_custom_dimension] = mock_rpc + request = {} + client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_custom_dimension_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.update_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomDimensionRequest() + +@pytest.mark.asyncio +async def test_update_custom_dimension_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_custom_dimension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_custom_dimension] = mock_object + + request = {} + await client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_custom_dimension_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateCustomDimensionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +@pytest.mark.asyncio +async def test_update_custom_dimension_async_from_dict(): + await test_update_custom_dimension_async(request_type=dict) + + +def test_update_custom_dimension_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCustomDimensionRequest() + + request.custom_dimension.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + call.return_value = resources.CustomDimension() + client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'custom_dimension.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_custom_dimension_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCustomDimensionRequest() + + request.custom_dimension.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + await client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'custom_dimension.name=name_value', + ) in kw['metadata'] + + +def test_update_custom_dimension_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_custom_dimension( + custom_dimension=resources.CustomDimension(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].custom_dimension + mock_val = resources.CustomDimension(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_custom_dimension_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension( + analytics_admin.UpdateCustomDimensionRequest(), + custom_dimension=resources.CustomDimension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_custom_dimension_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_custom_dimension( + custom_dimension=resources.CustomDimension(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].custom_dimension + mock_val = resources.CustomDimension(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_custom_dimension_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_dimension( + analytics_admin.UpdateCustomDimensionRequest(), + custom_dimension=resources.CustomDimension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCustomDimensionsRequest, + dict, +]) +def test_list_custom_dimensions(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomDimensionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCustomDimensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomDimensionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_custom_dimensions_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimensions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_custom_dimensions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomDimensionsRequest() + + +def test_list_custom_dimensions_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCustomDimensionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_custom_dimensions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomDimensionsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_custom_dimensions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_custom_dimensions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_custom_dimensions] = mock_rpc + request = {} + client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_custom_dimensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_custom_dimensions_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomDimensionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_custom_dimensions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomDimensionsRequest() + +@pytest.mark.asyncio +async def test_list_custom_dimensions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_custom_dimensions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_custom_dimensions] = mock_object + + request = {} + await client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_custom_dimensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_custom_dimensions_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListCustomDimensionsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomDimensionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCustomDimensionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomDimensionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_custom_dimensions_async_from_dict(): + await test_list_custom_dimensions_async(request_type=dict) + + +def test_list_custom_dimensions_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCustomDimensionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + call.return_value = analytics_admin.ListCustomDimensionsResponse() + client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimensions_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCustomDimensionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomDimensionsResponse()) + await client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimensions_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomDimensionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_custom_dimensions( + 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_custom_dimensions_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimensions( + analytics_admin.ListCustomDimensionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_custom_dimensions_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomDimensionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomDimensionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_custom_dimensions( + 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_custom_dimensions_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_dimensions( + analytics_admin.ListCustomDimensionsRequest(), + parent='parent_value', + ) + + +def test_list_custom_dimensions_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_custom_dimensions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_custom_dimensions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomDimension) + for i in results) +def test_list_custom_dimensions_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_custom_dimensions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + RuntimeError, + ) + pages = list(client.list_custom_dimensions(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_custom_dimensions_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_custom_dimensions(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, resources.CustomDimension) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_custom_dimensions_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_dimensions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + 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_custom_dimensions(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", [ + analytics_admin.ArchiveCustomDimensionRequest, + dict, +]) +def test_archive_custom_dimension(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_archive_custom_dimension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomDimensionRequest() + + +def test_archive_custom_dimension_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ArchiveCustomDimensionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_custom_dimension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomDimensionRequest( + name='name_value', + ) + +def test_archive_custom_dimension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_custom_dimension] = mock_rpc + request = {} + client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_custom_dimension_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 = AnalyticsAdminServiceAsyncClient( + 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.archive_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomDimensionRequest() + +@pytest.mark.asyncio +async def test_archive_custom_dimension_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.archive_custom_dimension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.archive_custom_dimension] = mock_object + + request = {} + await client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.archive_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_custom_dimension_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ArchiveCustomDimensionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_archive_custom_dimension_async_from_dict(): + await test_archive_custom_dimension_async(request_type=dict) + + +def test_archive_custom_dimension_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveCustomDimensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + call.return_value = None + client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_archive_custom_dimension_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveCustomDimensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_archive_custom_dimension_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__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.archive_custom_dimension( + 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_archive_custom_dimension_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.archive_custom_dimension( + analytics_admin.ArchiveCustomDimensionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_archive_custom_dimension_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_dimension), + '__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.archive_custom_dimension( + 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_archive_custom_dimension_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.archive_custom_dimension( + analytics_admin.ArchiveCustomDimensionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCustomDimensionRequest, + dict, +]) +def test_get_custom_dimension(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + ) + response = client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +def test_get_custom_dimension_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomDimensionRequest() + + +def test_get_custom_dimension_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetCustomDimensionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_custom_dimension(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomDimensionRequest( + name='name_value', + ) + +def test_get_custom_dimension_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_custom_dimension] = mock_rpc + request = {} + client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_custom_dimension_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.get_custom_dimension() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomDimensionRequest() + +@pytest.mark.asyncio +async def test_get_custom_dimension_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_custom_dimension in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_custom_dimension] = mock_object + + request = {} + await client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_custom_dimension_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetCustomDimensionRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=True, + )) + response = await client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCustomDimensionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + + +@pytest.mark.asyncio +async def test_get_custom_dimension_async_from_dict(): + await test_get_custom_dimension_async(request_type=dict) + + +def test_get_custom_dimension_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCustomDimensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + call.return_value = resources.CustomDimension() + client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimension_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCustomDimensionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + await client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_dimension_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_custom_dimension( + 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_custom_dimension_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_dimension( + analytics_admin.GetCustomDimensionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_custom_dimension_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_dimension), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomDimension() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomDimension()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_custom_dimension( + 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_custom_dimension_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_dimension( + analytics_admin.GetCustomDimensionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateCustomMetricRequest, + dict, +]) +def test_create_custom_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + response = client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +def test_create_custom_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomMetricRequest() + + +def test_create_custom_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateCustomMetricRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_custom_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomMetricRequest( + parent='parent_value', + ) + +def test_create_custom_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_custom_metric] = mock_rpc + request = {} + client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_custom_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.create_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateCustomMetricRequest() + +@pytest.mark.asyncio +async def test_create_custom_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_custom_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_custom_metric] = mock_object + + request = {} + await client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_custom_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateCustomMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +@pytest.mark.asyncio +async def test_create_custom_metric_async_from_dict(): + await test_create_custom_metric_async(request_type=dict) + + +def test_create_custom_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCustomMetricRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + call.return_value = resources.CustomMetric() + client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateCustomMetricRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + await client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_custom_metric( + parent='parent_value', + custom_metric=resources.CustomMetric(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].custom_metric + mock_val = resources.CustomMetric(name='name_value') + assert arg == mock_val + + +def test_create_custom_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric( + analytics_admin.CreateCustomMetricRequest(), + parent='parent_value', + custom_metric=resources.CustomMetric(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_custom_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_custom_metric( + parent='parent_value', + custom_metric=resources.CustomMetric(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].custom_metric + mock_val = resources.CustomMetric(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_custom_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_metric( + analytics_admin.CreateCustomMetricRequest(), + parent='parent_value', + custom_metric=resources.CustomMetric(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateCustomMetricRequest, + dict, +]) +def test_update_custom_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + response = client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +def test_update_custom_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomMetricRequest() + + +def test_update_custom_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateCustomMetricRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_custom_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomMetricRequest( + ) + +def test_update_custom_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_custom_metric] = mock_rpc + request = {} + client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_custom_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.update_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateCustomMetricRequest() + +@pytest.mark.asyncio +async def test_update_custom_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_custom_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_custom_metric] = mock_object + + request = {} + await client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_custom_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateCustomMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +@pytest.mark.asyncio +async def test_update_custom_metric_async_from_dict(): + await test_update_custom_metric_async(request_type=dict) + + +def test_update_custom_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCustomMetricRequest() + + request.custom_metric.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + call.return_value = resources.CustomMetric() + client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'custom_metric.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_custom_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateCustomMetricRequest() + + request.custom_metric.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + await client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'custom_metric.name=name_value', + ) in kw['metadata'] + + +def test_update_custom_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_custom_metric( + custom_metric=resources.CustomMetric(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].custom_metric + mock_val = resources.CustomMetric(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_custom_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric( + analytics_admin.UpdateCustomMetricRequest(), + custom_metric=resources.CustomMetric(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_custom_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_custom_metric( + custom_metric=resources.CustomMetric(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].custom_metric + mock_val = resources.CustomMetric(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_custom_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_metric( + analytics_admin.UpdateCustomMetricRequest(), + custom_metric=resources.CustomMetric(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCustomMetricsRequest, + dict, +]) +def test_list_custom_metrics(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomMetricsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCustomMetricsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomMetricsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_custom_metrics_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_metrics), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_custom_metrics() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomMetricsRequest() + + +def test_list_custom_metrics_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCustomMetricsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_custom_metrics(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomMetricsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_custom_metrics_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_custom_metrics in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_custom_metrics] = mock_rpc + request = {} + client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_custom_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_custom_metrics_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomMetricsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_custom_metrics() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListCustomMetricsRequest() + +@pytest.mark.asyncio +async def test_list_custom_metrics_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_custom_metrics in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_custom_metrics] = mock_object + + request = {} + await client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_custom_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_custom_metrics_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListCustomMetricsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomMetricsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListCustomMetricsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomMetricsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_custom_metrics_async_from_dict(): + await test_list_custom_metrics_async(request_type=dict) + + +def test_list_custom_metrics_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCustomMetricsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + call.return_value = analytics_admin.ListCustomMetricsResponse() + client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metrics_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListCustomMetricsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomMetricsResponse()) + await client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metrics_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomMetricsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_custom_metrics( + 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_custom_metrics_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_metrics( + analytics_admin.ListCustomMetricsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_custom_metrics_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListCustomMetricsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListCustomMetricsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_custom_metrics( + 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_custom_metrics_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_metrics( + analytics_admin.ListCustomMetricsRequest(), + parent='parent_value', + ) + + +def test_list_custom_metrics_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_custom_metrics), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_custom_metrics(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomMetric) + for i in results) +def test_list_custom_metrics_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + 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_custom_metrics), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, + ) + pages = list(client.list_custom_metrics(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_custom_metrics_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_custom_metrics(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, resources.CustomMetric) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_custom_metrics_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_custom_metrics), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + 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_custom_metrics(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", [ + analytics_admin.ArchiveCustomMetricRequest, + dict, +]) +def test_archive_custom_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_archive_custom_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomMetricRequest() + + +def test_archive_custom_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.ArchiveCustomMetricRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.archive_custom_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomMetricRequest( + name='name_value', + ) + +def test_archive_custom_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_custom_metric] = mock_rpc + request = {} + client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_custom_metric_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 = AnalyticsAdminServiceAsyncClient( + 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.archive_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ArchiveCustomMetricRequest() + +@pytest.mark.asyncio +async def test_archive_custom_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.archive_custom_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.archive_custom_metric] = mock_object + + request = {} + await client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.archive_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_archive_custom_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ArchiveCustomMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ArchiveCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_archive_custom_metric_async_from_dict(): + await test_archive_custom_metric_async(request_type=dict) + + +def test_archive_custom_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveCustomMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + call.return_value = None + client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_archive_custom_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ArchiveCustomMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_archive_custom_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__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.archive_custom_metric( + 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_archive_custom_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.archive_custom_metric( + analytics_admin.ArchiveCustomMetricRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_archive_custom_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.archive_custom_metric), + '__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.archive_custom_metric( + 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_archive_custom_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.archive_custom_metric( + analytics_admin.ArchiveCustomMetricRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCustomMetricRequest, + dict, +]) +def test_get_custom_metric(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + response = client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +def test_get_custom_metric_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomMetricRequest() + + +def test_get_custom_metric_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetCustomMetricRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_custom_metric(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomMetricRequest( + name='name_value', + ) + +def test_get_custom_metric_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_custom_metric] = mock_rpc + request = {} + client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_custom_metric_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 = AnalyticsAdminServiceAsyncClient( + 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.get_custom_metric() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetCustomMetricRequest() + +@pytest.mark.asyncio +async def test_get_custom_metric_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_custom_metric in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_custom_metric] = mock_object + + request = {} + await client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_custom_metric_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetCustomMetricRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + )) + response = await client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetCustomMetricRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + + +@pytest.mark.asyncio +async def test_get_custom_metric_async_from_dict(): + await test_get_custom_metric_async(request_type=dict) + + +def test_get_custom_metric_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCustomMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + call.return_value = resources.CustomMetric() + client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metric_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetCustomMetricRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + await client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_custom_metric_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_custom_metric( + 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_custom_metric_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=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_custom_metric( + analytics_admin.GetCustomMetricRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_custom_metric_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_custom_metric), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CustomMetric() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CustomMetric()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_custom_metric( + 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_custom_metric_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_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_custom_metric( + analytics_admin.GetCustomMetricRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataRetentionSettingsRequest, + dict, +]) +def test_get_data_retention_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + ) + response = client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataRetentionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + + +def test_get_data_retention_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_retention_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataRetentionSettingsRequest() + + +def test_get_data_retention_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetDataRetentionSettingsRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_retention_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataRetentionSettingsRequest( + name='name_value', + ) + +def test_get_data_retention_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_retention_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_retention_settings] = mock_rpc + request = {} + client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_retention_settings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + )) + response = await client.get_data_retention_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataRetentionSettingsRequest() + +@pytest.mark.asyncio +async def test_get_data_retention_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_data_retention_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_data_retention_settings] = mock_object + + request = {} + await client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_retention_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetDataRetentionSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + )) + response = await client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataRetentionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + + +@pytest.mark.asyncio +async def test_get_data_retention_settings_async_from_dict(): + await test_get_data_retention_settings_async(request_type=dict) + + +def test_get_data_retention_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataRetentionSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + call.return_value = resources.DataRetentionSettings() + client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_data_retention_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataRetentionSettingsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings()) + await client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_data_retention_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_retention_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_data_retention_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_retention_settings( + analytics_admin.GetDataRetentionSettingsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_retention_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_retention_settings( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_data_retention_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_retention_settings( + analytics_admin.GetDataRetentionSettingsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDataRetentionSettingsRequest, + dict, +]) +def test_update_data_retention_settings(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + ) + response = client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataRetentionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + + +def test_update_data_retention_settings_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_retention_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() + + +def test_update_data_retention_settings_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateDataRetentionSettingsRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_retention_settings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest( + ) + +def test_update_data_retention_settings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_retention_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_retention_settings] = mock_rpc + request = {} + client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_retention_settings_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 = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + )) + response = await client.update_data_retention_settings() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataRetentionSettingsRequest() + +@pytest.mark.asyncio +async def test_update_data_retention_settings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_data_retention_settings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_data_retention_settings] = mock_object + + request = {} + await client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_retention_settings_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateDataRetentionSettingsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=True, + )) + response = await client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataRetentionSettingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + + +@pytest.mark.asyncio +async def test_update_data_retention_settings_async_from_dict(): + await test_update_data_retention_settings_async(request_type=dict) + + +def test_update_data_retention_settings_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataRetentionSettingsRequest() + + request.data_retention_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + call.return_value = resources.DataRetentionSettings() + client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_retention_settings.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_data_retention_settings_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataRetentionSettingsRequest() + + request.data_retention_settings.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings()) + await client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_retention_settings.name=name_value', + ) in kw['metadata'] + + +def test_update_data_retention_settings_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_retention_settings( + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].data_retention_settings + mock_val = resources.DataRetentionSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_data_retention_settings_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_retention_settings( + analytics_admin.UpdateDataRetentionSettingsRequest(), + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_data_retention_settings_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_retention_settings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataRetentionSettings() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataRetentionSettings()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_retention_settings( + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].data_retention_settings + mock_val = resources.DataRetentionSettings(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_data_retention_settings_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_data_retention_settings( + analytics_admin.UpdateDataRetentionSettingsRequest(), + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateDataStreamRequest, + dict, +]) +def test_create_data_stream(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + ) + response = client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +def test_create_data_stream_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDataStreamRequest() + + +def test_create_data_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.CreateDataStreamRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_data_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDataStreamRequest( + parent='parent_value', + ) + +def test_create_data_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_data_stream] = mock_rpc + request = {} + client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_data_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.create_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.CreateDataStreamRequest() + +@pytest.mark.asyncio +async def test_create_data_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_data_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.create_data_stream] = mock_object + + request = {} + await client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_create_data_stream_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.CreateDataStreamRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.CreateDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_create_data_stream_async_from_dict(): + await test_create_data_stream_async(request_type=dict) + + +def test_create_data_stream_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateDataStreamRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + call.return_value = resources.DataStream() + client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_data_stream_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.CreateDataStreamRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + await client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_data_stream_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_data_stream( + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_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].data_stream + mock_val = resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')) + assert arg == mock_val + + +def test_create_data_stream_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_data_stream( + analytics_admin.CreateDataStreamRequest(), + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + ) + +@pytest.mark.asyncio +async def test_create_data_stream_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_data_stream( + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_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].data_stream + mock_val = resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_data_stream_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_data_stream( + analytics_admin.CreateDataStreamRequest(), + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteDataStreamRequest, + dict, +]) +def test_delete_data_stream(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_data_stream_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDataStreamRequest() + + +def test_delete_data_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.DeleteDataStreamRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.delete_data_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDataStreamRequest( + name='name_value', + ) + +def test_delete_data_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_data_stream] = mock_rpc + request = {} + client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_data_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.DeleteDataStreamRequest() + +@pytest.mark.asyncio +async def test_delete_data_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.delete_data_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.delete_data_stream] = mock_object + + request = {} + await client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.delete_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_delete_data_stream_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.DeleteDataStreamRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.DeleteDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_data_stream_async_from_dict(): + await test_delete_data_stream_async(request_type=dict) + + +def test_delete_data_stream_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteDataStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + call.return_value = None + client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_data_stream_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.DeleteDataStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_data_stream_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_data_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_data_stream_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_data_stream( + analytics_admin.DeleteDataStreamRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_data_stream_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_data_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_data_stream_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_data_stream( + analytics_admin.DeleteDataStreamRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDataStreamRequest, + dict, +]) +def test_update_data_stream(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + ) + response = client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +def test_update_data_stream_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataStreamRequest() + + +def test_update_data_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.UpdateDataStreamRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_data_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataStreamRequest( + ) + +def test_update_data_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_stream] = mock_rpc + request = {} + client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.update_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.UpdateDataStreamRequest() + +@pytest.mark.asyncio +async def test_update_data_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_data_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.update_data_stream] = mock_object + + request = {} + await client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_update_data_stream_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.UpdateDataStreamRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.UpdateDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_update_data_stream_async_from_dict(): + await test_update_data_stream_async(request_type=dict) + + +def test_update_data_stream_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataStreamRequest() + + request.data_stream.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + call.return_value = resources.DataStream() + client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_stream.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_data_stream_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.UpdateDataStreamRequest() + + request.data_stream.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + await client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'data_stream.name=name_value', + ) in kw['metadata'] + + +def test_update_data_stream_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_data_stream( + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].data_stream + mock_val = resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_data_stream_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_stream( + analytics_admin.UpdateDataStreamRequest(), + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_data_stream_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_data_stream( + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].data_stream + mock_val = resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_data_stream_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_data_stream( + analytics_admin.UpdateDataStreamRequest(), + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListDataStreamsRequest, + dict, +]) +def test_list_data_streams(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDataStreamsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListDataStreamsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataStreamsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_data_streams_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_data_streams() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDataStreamsRequest() + + +def test_list_data_streams_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListDataStreamsRequest( + parent='parent_value', + page_token='page_token_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_data_streams(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDataStreamsRequest( + parent='parent_value', + page_token='page_token_value', + ) + +def test_list_data_streams_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_streams in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_data_streams] = mock_rpc + request = {} + client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_data_streams_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDataStreamsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_streams() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.ListDataStreamsRequest() + +@pytest.mark.asyncio +async def test_list_data_streams_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_data_streams in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.list_data_streams] = mock_object + + request = {} + await client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_data_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_list_data_streams_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.ListDataStreamsRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDataStreamsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.ListDataStreamsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataStreamsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_data_streams_async_from_dict(): + await test_list_data_streams_async(request_type=dict) + + +def test_list_data_streams_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListDataStreamsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + call.return_value = analytics_admin.ListDataStreamsResponse() + client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_data_streams_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.ListDataStreamsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDataStreamsResponse()) + await client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_data_streams_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDataStreamsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_streams( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_data_streams_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_streams( + analytics_admin.ListDataStreamsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_data_streams_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.ListDataStreamsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.ListDataStreamsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_data_streams( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_data_streams_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_data_streams( + analytics_admin.ListDataStreamsRequest(), + parent='parent_value', + ) + + +def test_list_data_streams_pager(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_data_streams(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DataStream) + for i in results) +def test_list_data_streams_pages(transport_name: str = "grpc"): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_streams(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_data_streams_async_pager(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_streams(request={},) + assert async_pager.next_page_token == 'abc' + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.DataStream) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_data_streams_async_pages(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_streams), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_data_streams(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataStreamRequest, + dict, +]) +def test_get_data_stream(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + ) + response = client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +def test_get_data_stream_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataStreamRequest() + + +def test_get_data_stream_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.GetDataStreamRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_data_stream(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataStreamRequest( + name='name_value', + ) + +def test_get_data_stream_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_stream] = mock_rpc + request = {} + client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_stream_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc_asyncio', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.get_data_stream() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.GetDataStreamRequest() + +@pytest.mark.asyncio +async def test_get_data_stream_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_data_stream in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.get_data_stream] = mock_object + + request = {} + await client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_get_data_stream_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.GetDataStreamRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_name_value', + )) + response = await client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.GetDataStreamRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + + +@pytest.mark.asyncio +async def test_get_data_stream_async_from_dict(): + await test_get_data_stream_async(request_type=dict) + + +def test_get_data_stream_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + call.return_value = resources.DataStream() + client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_data_stream_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.GetDataStreamRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + await client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_data_stream_flattened(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_data_stream_flattened_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_stream( + analytics_admin.GetDataStreamRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_data_stream_flattened_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_stream), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.DataStream() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.DataStream()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_stream( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_data_stream_flattened_error_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_data_stream( + analytics_admin.GetDataStreamRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.RunAccessReportRequest, + dict, +]) +def test_run_access_report(request_type, transport: str = 'grpc'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = analytics_admin.RunAccessReportResponse( + row_count=992, + ) + response = client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = analytics_admin.RunAccessReportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.RunAccessReportResponse) + assert response.row_count == 992 + + +def test_run_access_report_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_access_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.RunAccessReportRequest() + + +def test_run_access_report_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 = AnalyticsAdminServiceClient( + 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 = analytics_admin.RunAccessReportRequest( + entity='entity_value', + time_zone='time_zone_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.run_access_report(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.RunAccessReportRequest( + entity='entity_value', + time_zone='time_zone_value', + ) + +def test_run_access_report_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_access_report in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_access_report] = mock_rpc + request = {} + client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_access_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_run_access_report_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 = AnalyticsAdminServiceAsyncClient( + 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.run_access_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.RunAccessReportResponse( + row_count=992, + )) + response = await client.run_access_report() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == analytics_admin.RunAccessReportRequest() + +@pytest.mark.asyncio +async def test_run_access_report_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.run_access_report in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_object = mock.AsyncMock() + client._client._transport._wrapped_methods[client._client._transport.run_access_report] = mock_object + + request = {} + await client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.run_access_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + +@pytest.mark.asyncio +async def test_run_access_report_async(transport: str = 'grpc_asyncio', request_type=analytics_admin.RunAccessReportRequest): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.RunAccessReportResponse( + row_count=992, + )) + response = await client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = analytics_admin.RunAccessReportRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.RunAccessReportResponse) + assert response.row_count == 992 + + +@pytest.mark.asyncio +async def test_run_access_report_async_from_dict(): + await test_run_access_report_async(request_type=dict) + + +def test_run_access_report_field_headers(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.RunAccessReportRequest() + + request.entity = 'entity_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + call.return_value = analytics_admin.RunAccessReportResponse() + client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entity=entity_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_run_access_report_field_headers_async(): + client = AnalyticsAdminServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = analytics_admin.RunAccessReportRequest() + + request.entity = 'entity_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_access_report), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(analytics_admin.RunAccessReportResponse()) + await client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'entity=entity_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetAccountRequest, + dict, +]) +def test_get_account_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/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 = resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_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 = resources.Account.pb(return_value) + 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_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + +def test_get_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_account] = mock_rpc + + request = {} + client.get_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_account_rest_required_fields(request_type=analytics_admin.GetAccountRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_account._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_account._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Account() + # 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 = resources.Account.pb(return_value) + 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_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_account_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_account_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_account") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_account") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetAccountRequest.pb(analytics_admin.GetAccountRequest()) + 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 = resources.Account.to_json(resources.Account()) + + request = analytics_admin.GetAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Account() + + client.get_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_account_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetAccountRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/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_account(request) + + +def test_get_account_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Account() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/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 = resources.Account.pb(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_account(**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/v1beta/{name=accounts/*}" % client.transport._host, args[1]) + + +def test_get_account_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_account( + analytics_admin.GetAccountRequest(), + name='name_value', + ) + + +def test_get_account_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccountsRequest, + dict, +]) +def test_list_accounts_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccountsResponse( + 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 = analytics_admin.ListAccountsResponse.pb(return_value) + 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_accounts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_accounts_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_accounts in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_accounts] = mock_rpc + + request = {} + client.list_accounts(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_accounts(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_accounts_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_accounts") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_accounts") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListAccountsRequest.pb(analytics_admin.ListAccountsRequest()) + 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 = analytics_admin.ListAccountsResponse.to_json(analytics_admin.ListAccountsResponse()) + + request = analytics_admin.ListAccountsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListAccountsResponse() + + client.list_accounts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_accounts_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListAccountsRequest): + client = AnalyticsAdminServiceClient( + 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_accounts(request) + + +def test_list_accounts_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + resources.Account(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountsResponse( + accounts=[], + next_page_token='def', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountsResponse( + accounts=[ + resources.Account(), + resources.Account(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListAccountsResponse.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_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Account) + for i in results) + + pages = list(client.list_accounts(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", [ + analytics_admin.DeleteAccountRequest, + dict, +]) +def test_delete_account_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/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_account(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_account] = mock_rpc + + request = {} + client.delete_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_account_rest_required_fields(request_type=analytics_admin.DeleteAccountRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_account._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_account._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 = AnalyticsAdminServiceClient( + 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_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_account_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_account_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_account") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteAccountRequest.pb(analytics_admin.DeleteAccountRequest()) + 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 = analytics_admin.DeleteAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_account_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteAccountRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/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_account(request) + + +def test_delete_account_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'accounts/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_account(**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/v1beta/{name=accounts/*}" % client.transport._host, args[1]) + + +def test_delete_account_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_account( + analytics_admin.DeleteAccountRequest(), + name='name_value', + ) + + +def test_delete_account_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateAccountRequest, + dict, +]) +def test_update_account_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'account': {'name': 'accounts/sample1'}} + request_init["account"] = {'name': 'accounts/sample1', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'display_name': 'display_name_value', 'region_code': 'region_code_value', 'deleted': True, 'gmp_organization': 'gmp_organization_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 = analytics_admin.UpdateAccountRequest.meta.fields["account"] + + 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["account"].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["account"][field])): + del request_init["account"][field][i][subfield] + else: + del request_init["account"][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 = resources.Account( + name='name_value', + display_name='display_name_value', + region_code='region_code_value', + deleted=True, + gmp_organization='gmp_organization_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 = resources.Account.pb(return_value) + 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_account(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Account) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.region_code == 'region_code_value' + assert response.deleted is True + assert response.gmp_organization == 'gmp_organization_value' + +def test_update_account_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_account in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_account] = mock_rpc + + request = {} + client.update_account(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_account(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_account_rest_required_fields(request_type=analytics_admin.UpdateAccountRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_account._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_account._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Account() + # 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 = resources.Account.pb(return_value) + 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_account(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_account_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("account", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_account_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_account") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_account") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateAccountRequest.pb(analytics_admin.UpdateAccountRequest()) + 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 = resources.Account.to_json(resources.Account()) + + request = analytics_admin.UpdateAccountRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Account() + + client.update_account(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_account_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateAccountRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'account': {'name': 'accounts/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_account(request) + + +def test_update_account_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Account() + + # get arguments that satisfy an http rule for this method + sample_request = {'account': {'name': 'accounts/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + account=resources.Account(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 = resources.Account.pb(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_account(**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/v1beta/{account.name=accounts/*}" % client.transport._host, args[1]) + + +def test_update_account_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_account( + analytics_admin.UpdateAccountRequest(), + account=resources.Account(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_account_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ProvisionAccountTicketRequest, + dict, +]) +def test_provision_account_ticket_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ProvisionAccountTicketResponse( + account_ticket_id='account_ticket_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 = analytics_admin.ProvisionAccountTicketResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.provision_account_ticket(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.ProvisionAccountTicketResponse) + assert response.account_ticket_id == 'account_ticket_id_value' + +def test_provision_account_ticket_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.provision_account_ticket in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.provision_account_ticket] = mock_rpc + + request = {} + client.provision_account_ticket(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.provision_account_ticket(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_provision_account_ticket_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_provision_account_ticket") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_provision_account_ticket") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ProvisionAccountTicketRequest.pb(analytics_admin.ProvisionAccountTicketRequest()) + 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 = analytics_admin.ProvisionAccountTicketResponse.to_json(analytics_admin.ProvisionAccountTicketResponse()) + + request = analytics_admin.ProvisionAccountTicketRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ProvisionAccountTicketResponse() + + client.provision_account_ticket(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_provision_account_ticket_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ProvisionAccountTicketRequest): + client = AnalyticsAdminServiceClient( + 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.provision_account_ticket(request) + + +def test_provision_account_ticket_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListAccountSummariesRequest, + dict, +]) +def test_list_account_summaries_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListAccountSummariesResponse( + 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 = analytics_admin.ListAccountSummariesResponse.pb(return_value) + 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_account_summaries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAccountSummariesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_account_summaries_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_account_summaries in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_account_summaries] = mock_rpc + + request = {} + client.list_account_summaries(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_summaries(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_account_summaries_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_account_summaries") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_account_summaries") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListAccountSummariesRequest.pb(analytics_admin.ListAccountSummariesRequest()) + 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 = analytics_admin.ListAccountSummariesResponse.to_json(analytics_admin.ListAccountSummariesResponse()) + + request = analytics_admin.ListAccountSummariesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListAccountSummariesResponse() + + client.list_account_summaries(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_account_summaries_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListAccountSummariesRequest): + client = AnalyticsAdminServiceClient( + 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_account_summaries(request) + + +def test_list_account_summaries_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + resources.AccountSummary(), + ], + next_page_token='abc', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[], + next_page_token='def', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + ], + next_page_token='ghi', + ), + analytics_admin.ListAccountSummariesResponse( + account_summaries=[ + resources.AccountSummary(), + resources.AccountSummary(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListAccountSummariesResponse.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_account_summaries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.AccountSummary) + for i in results) + + pages = list(client.list_account_summaries(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", [ + analytics_admin.GetPropertyRequest, + dict, +]) +def test_get_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/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 = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_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 = resources.Property.pb(return_value) + 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_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + +def test_get_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_property] = mock_rpc + + request = {} + client.get_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_property_rest_required_fields(request_type=analytics_admin.GetPropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_property._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_property._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # 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 = resources.Property.pb(return_value) + 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_property(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetPropertyRequest.pb(analytics_admin.GetPropertyRequest()) + 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 = resources.Property.to_json(resources.Property()) + + request = analytics_admin.GetPropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.get_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetPropertyRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/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_property(request) + + +def test_get_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/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 = resources.Property.pb(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_property(**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/v1beta/{name=properties/*}" % client.transport._host, args[1]) + + +def test_get_property_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_property( + analytics_admin.GetPropertyRequest(), + name='name_value', + ) + + +def test_get_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListPropertiesRequest, + dict, +]) +def test_list_properties_rest(request_type): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListPropertiesResponse( + 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 = analytics_admin.ListPropertiesResponse.pb(return_value) + 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_properties(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPropertiesPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_properties_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_properties in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_properties] = mock_rpc + + request = {} + client.list_properties(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_properties(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_properties_rest_required_fields(request_type=analytics_admin.ListPropertiesRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["filter"] = "" + 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 "filter" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_properties._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "filter" in jsonified_request + assert jsonified_request["filter"] == request_init["filter"] + + jsonified_request["filter"] = 'filter_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_properties._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_deleted", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "filter" in jsonified_request + assert jsonified_request["filter"] == 'filter_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListPropertiesResponse() + # 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 = analytics_admin.ListPropertiesResponse.pb(return_value) + 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_properties(request) + + expected_params = [ + ( + "filter", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_properties_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_properties._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", "showDeleted", )) & set(("filter", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_properties_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_properties") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_properties") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListPropertiesRequest.pb(analytics_admin.ListPropertiesRequest()) + 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 = analytics_admin.ListPropertiesResponse.to_json(analytics_admin.ListPropertiesResponse()) + + request = analytics_admin.ListPropertiesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListPropertiesResponse() + + client.list_properties(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_properties_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListPropertiesRequest): + client = AnalyticsAdminServiceClient( + 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_properties(request) + + +def test_list_properties_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + resources.Property(), + ], + next_page_token='abc', + ), + analytics_admin.ListPropertiesResponse( + properties=[], + next_page_token='def', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + ], + next_page_token='ghi', + ), + analytics_admin.ListPropertiesResponse( + properties=[ + resources.Property(), + resources.Property(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListPropertiesResponse.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_properties(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Property) + for i in results) + + pages = list(client.list_properties(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", [ + analytics_admin.CreatePropertyRequest, + dict, +]) +def test_create_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["property"] = {'name': 'name_value', 'property_type': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'parent': 'parent_value', 'display_name': 'display_name_value', 'industry_category': 1, 'time_zone': 'time_zone_value', 'currency_code': 'currency_code_value', 'service_level': 1, 'delete_time': {}, 'expire_time': {}, 'account': 'account_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 = analytics_admin.CreatePropertyRequest.meta.fields["property"] + + 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["property"].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["property"][field])): + del request_init["property"][field][i][subfield] + else: + del request_init["property"][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 = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_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 = resources.Property.pb(return_value) + 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_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + +def test_create_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_property] = mock_rpc + + request = {} + client.create_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_property_rest_required_fields(request_type=analytics_admin.CreatePropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_property._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_property._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # 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 = resources.Property.pb(return_value) + 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_property(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("property", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreatePropertyRequest.pb(analytics_admin.CreatePropertyRequest()) + 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 = resources.Property.to_json(resources.Property()) + + request = analytics_admin.CreatePropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.create_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreatePropertyRequest): + client = AnalyticsAdminServiceClient( + 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_property(request) + + +def test_create_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + property=resources.Property(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 = resources.Property.pb(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_property(**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/v1beta/properties" % client.transport._host, args[1]) + + +def test_create_property_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_property( + analytics_admin.CreatePropertyRequest(), + property=resources.Property(name='name_value'), + ) + + +def test_create_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeletePropertyRequest, + dict, +]) +def test_delete_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/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 = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_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 = resources.Property.pb(return_value) + 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_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + +def test_delete_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_property] = mock_rpc + + request = {} + client.delete_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_property_rest_required_fields(request_type=analytics_admin.DeletePropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_property._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_property._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # 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 = resources.Property.pb(return_value) + 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_property(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_delete_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_delete_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.DeletePropertyRequest.pb(analytics_admin.DeletePropertyRequest()) + 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 = resources.Property.to_json(resources.Property()) + + request = analytics_admin.DeletePropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.delete_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeletePropertyRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/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_property(request) + + +def test_delete_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/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 = resources.Property.pb(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_property(**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/v1beta/{name=properties/*}" % client.transport._host, args[1]) + + +def test_delete_property_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_property( + analytics_admin.DeletePropertyRequest(), + name='name_value', + ) + + +def test_delete_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdatePropertyRequest, + dict, +]) +def test_update_property_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'property': {'name': 'properties/sample1'}} + request_init["property"] = {'name': 'properties/sample1', 'property_type': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'parent': 'parent_value', 'display_name': 'display_name_value', 'industry_category': 1, 'time_zone': 'time_zone_value', 'currency_code': 'currency_code_value', 'service_level': 1, 'delete_time': {}, 'expire_time': {}, 'account': 'account_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 = analytics_admin.UpdatePropertyRequest.meta.fields["property"] + + 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["property"].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["property"][field])): + del request_init["property"][field][i][subfield] + else: + del request_init["property"][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 = resources.Property( + name='name_value', + property_type=resources.PropertyType.PROPERTY_TYPE_ORDINARY, + parent='parent_value', + display_name='display_name_value', + industry_category=resources.IndustryCategory.AUTOMOTIVE, + time_zone='time_zone_value', + currency_code='currency_code_value', + service_level=resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD, + account='account_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 = resources.Property.pb(return_value) + 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_property(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Property) + assert response.name == 'name_value' + assert response.property_type == resources.PropertyType.PROPERTY_TYPE_ORDINARY + assert response.parent == 'parent_value' + assert response.display_name == 'display_name_value' + assert response.industry_category == resources.IndustryCategory.AUTOMOTIVE + assert response.time_zone == 'time_zone_value' + assert response.currency_code == 'currency_code_value' + assert response.service_level == resources.ServiceLevel.GOOGLE_ANALYTICS_STANDARD + assert response.account == 'account_value' + +def test_update_property_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_property in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_property] = mock_rpc + + request = {} + client.update_property(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_property(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_property_rest_required_fields(request_type=analytics_admin.UpdatePropertyRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_property._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_property._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Property() + # 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 = resources.Property.pb(return_value) + 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_property(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_property_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_property._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("property", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_property_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_property") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_property") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdatePropertyRequest.pb(analytics_admin.UpdatePropertyRequest()) + 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 = resources.Property.to_json(resources.Property()) + + request = analytics_admin.UpdatePropertyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Property() + + client.update_property(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_property_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdatePropertyRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'property': {'name': 'properties/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_property(request) + + +def test_update_property_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.Property() + + # get arguments that satisfy an http rule for this method + sample_request = {'property': {'name': 'properties/sample1'}} + + # get truthy value for each flattened field + mock_args = dict( + property=resources.Property(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 = resources.Property.pb(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_property(**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/v1beta/{property.name=properties/*}" % client.transport._host, args[1]) + + +def test_update_property_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_property( + analytics_admin.UpdatePropertyRequest(), + property=resources.Property(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_property_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateFirebaseLinkRequest, + dict, +]) +def test_create_firebase_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["firebase_link"] = {'name': 'name_value', 'project': 'project_value', 'create_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 = analytics_admin.CreateFirebaseLinkRequest.meta.fields["firebase_link"] + + 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["firebase_link"].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["firebase_link"][field])): + del request_init["firebase_link"][field][i][subfield] + else: + del request_init["firebase_link"][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 = resources.FirebaseLink( + name='name_value', + project='project_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 = resources.FirebaseLink.pb(return_value) + 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_firebase_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.FirebaseLink) + assert response.name == 'name_value' + assert response.project == 'project_value' + +def test_create_firebase_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_firebase_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_firebase_link] = mock_rpc + + request = {} + client.create_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_firebase_link_rest_required_fields(request_type=analytics_admin.CreateFirebaseLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_firebase_link._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_firebase_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.FirebaseLink() + # 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 = resources.FirebaseLink.pb(return_value) + 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_firebase_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_firebase_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_firebase_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "firebaseLink", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_firebase_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_firebase_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_firebase_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateFirebaseLinkRequest.pb(analytics_admin.CreateFirebaseLinkRequest()) + 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 = resources.FirebaseLink.to_json(resources.FirebaseLink()) + + request = analytics_admin.CreateFirebaseLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.FirebaseLink() + + client.create_firebase_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_firebase_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateFirebaseLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_firebase_link(request) + + +def test_create_firebase_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.FirebaseLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + firebase_link=resources.FirebaseLink(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 = resources.FirebaseLink.pb(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_firebase_link(**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/v1beta/{parent=properties/*}/firebaseLinks" % client.transport._host, args[1]) + + +def test_create_firebase_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_firebase_link( + analytics_admin.CreateFirebaseLinkRequest(), + parent='parent_value', + firebase_link=resources.FirebaseLink(name='name_value'), + ) + + +def test_create_firebase_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteFirebaseLinkRequest, + dict, +]) +def test_delete_firebase_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/firebaseLinks/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_firebase_link(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_firebase_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_firebase_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_firebase_link] = mock_rpc + + request = {} + client.delete_firebase_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_firebase_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_firebase_link_rest_required_fields(request_type=analytics_admin.DeleteFirebaseLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_firebase_link._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_firebase_link._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 = AnalyticsAdminServiceClient( + 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_firebase_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_firebase_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_firebase_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_firebase_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_firebase_link") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteFirebaseLinkRequest.pb(analytics_admin.DeleteFirebaseLinkRequest()) + 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 = analytics_admin.DeleteFirebaseLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_firebase_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_firebase_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteFirebaseLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/firebaseLinks/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_firebase_link(request) + + +def test_delete_firebase_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/firebaseLinks/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_firebase_link(**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/v1beta/{name=properties/*/firebaseLinks/*}" % client.transport._host, args[1]) + + +def test_delete_firebase_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_firebase_link( + analytics_admin.DeleteFirebaseLinkRequest(), + name='name_value', + ) + + +def test_delete_firebase_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListFirebaseLinksRequest, + dict, +]) +def test_list_firebase_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListFirebaseLinksResponse( + 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 = analytics_admin.ListFirebaseLinksResponse.pb(return_value) + 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_firebase_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFirebaseLinksPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_firebase_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_firebase_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_firebase_links] = mock_rpc + + request = {} + client.list_firebase_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_firebase_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_firebase_links_rest_required_fields(request_type=analytics_admin.ListFirebaseLinksRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_firebase_links._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_firebase_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListFirebaseLinksResponse() + # 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 = analytics_admin.ListFirebaseLinksResponse.pb(return_value) + 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_firebase_links(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_firebase_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_firebase_links._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_firebase_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_firebase_links") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_firebase_links") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListFirebaseLinksRequest.pb(analytics_admin.ListFirebaseLinksRequest()) + 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 = analytics_admin.ListFirebaseLinksResponse.to_json(analytics_admin.ListFirebaseLinksResponse()) + + request = analytics_admin.ListFirebaseLinksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListFirebaseLinksResponse() + + client.list_firebase_links(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_firebase_links_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListFirebaseLinksRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_firebase_links(request) + + +def test_list_firebase_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListFirebaseLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListFirebaseLinksResponse.pb(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_firebase_links(**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/v1beta/{parent=properties/*}/firebaseLinks" % client.transport._host, args[1]) + + +def test_list_firebase_links_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_firebase_links( + analytics_admin.ListFirebaseLinksRequest(), + parent='parent_value', + ) + + +def test_list_firebase_links_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[], + next_page_token='def', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListFirebaseLinksResponse( + firebase_links=[ + resources.FirebaseLink(), + resources.FirebaseLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListFirebaseLinksResponse.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': 'properties/sample1'} + + pager = client.list_firebase_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.FirebaseLink) + for i in results) + + pages = list(client.list_firebase_links(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", [ + analytics_admin.CreateGoogleAdsLinkRequest, + dict, +]) +def test_create_google_ads_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["google_ads_link"] = {'name': 'name_value', 'customer_id': 'customer_id_value', 'can_manage_clients': True, 'ads_personalization_enabled': {'value': True}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'creator_email_address': 'creator_email_address_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 = analytics_admin.CreateGoogleAdsLinkRequest.meta.fields["google_ads_link"] + + 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["google_ads_link"].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["google_ads_link"][field])): + del request_init["google_ads_link"][field][i][subfield] + else: + del request_init["google_ads_link"][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 = resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_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 = resources.GoogleAdsLink.pb(return_value) + 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_google_ads_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + +def test_create_google_ads_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_google_ads_link] = mock_rpc + + request = {} + client.create_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_google_ads_link_rest_required_fields(request_type=analytics_admin.CreateGoogleAdsLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_ads_link._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_google_ads_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.GoogleAdsLink() + # 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 = resources.GoogleAdsLink.pb(return_value) + 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_google_ads_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_google_ads_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_google_ads_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "googleAdsLink", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_google_ads_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_google_ads_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_google_ads_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateGoogleAdsLinkRequest.pb(analytics_admin.CreateGoogleAdsLinkRequest()) + 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 = resources.GoogleAdsLink.to_json(resources.GoogleAdsLink()) + + request = analytics_admin.CreateGoogleAdsLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.GoogleAdsLink() + + client.create_google_ads_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_google_ads_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateGoogleAdsLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_google_ads_link(request) + + +def test_create_google_ads_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.GoogleAdsLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(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 = resources.GoogleAdsLink.pb(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_google_ads_link(**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/v1beta/{parent=properties/*}/googleAdsLinks" % client.transport._host, args[1]) + + +def test_create_google_ads_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_ads_link( + analytics_admin.CreateGoogleAdsLinkRequest(), + parent='parent_value', + google_ads_link=resources.GoogleAdsLink(name='name_value'), + ) + + +def test_create_google_ads_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateGoogleAdsLinkRequest, + dict, +]) +def test_update_google_ads_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'google_ads_link': {'name': 'properties/sample1/googleAdsLinks/sample2'}} + request_init["google_ads_link"] = {'name': 'properties/sample1/googleAdsLinks/sample2', 'customer_id': 'customer_id_value', 'can_manage_clients': True, 'ads_personalization_enabled': {'value': True}, 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'creator_email_address': 'creator_email_address_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 = analytics_admin.UpdateGoogleAdsLinkRequest.meta.fields["google_ads_link"] + + 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["google_ads_link"].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["google_ads_link"][field])): + del request_init["google_ads_link"][field][i][subfield] + else: + del request_init["google_ads_link"][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 = resources.GoogleAdsLink( + name='name_value', + customer_id='customer_id_value', + can_manage_clients=True, + creator_email_address='creator_email_address_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 = resources.GoogleAdsLink.pb(return_value) + 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_google_ads_link(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.GoogleAdsLink) + assert response.name == 'name_value' + assert response.customer_id == 'customer_id_value' + assert response.can_manage_clients is True + assert response.creator_email_address == 'creator_email_address_value' + +def test_update_google_ads_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_google_ads_link] = mock_rpc + + request = {} + client.update_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_google_ads_link_rest_required_fields(request_type=analytics_admin.UpdateGoogleAdsLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_ads_link._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_google_ads_link._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.GoogleAdsLink() + # 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 = resources.GoogleAdsLink.pb(return_value) + 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_google_ads_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_google_ads_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_google_ads_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_google_ads_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_google_ads_link") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_google_ads_link") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateGoogleAdsLinkRequest.pb(analytics_admin.UpdateGoogleAdsLinkRequest()) + 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 = resources.GoogleAdsLink.to_json(resources.GoogleAdsLink()) + + request = analytics_admin.UpdateGoogleAdsLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.GoogleAdsLink() + + client.update_google_ads_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_google_ads_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateGoogleAdsLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'google_ads_link': {'name': 'properties/sample1/googleAdsLinks/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_google_ads_link(request) + + +def test_update_google_ads_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.GoogleAdsLink() + + # get arguments that satisfy an http rule for this method + sample_request = {'google_ads_link': {'name': 'properties/sample1/googleAdsLinks/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + google_ads_link=resources.GoogleAdsLink(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 = resources.GoogleAdsLink.pb(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_google_ads_link(**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/v1beta/{google_ads_link.name=properties/*/googleAdsLinks/*}" % client.transport._host, args[1]) + + +def test_update_google_ads_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_ads_link( + analytics_admin.UpdateGoogleAdsLinkRequest(), + google_ads_link=resources.GoogleAdsLink(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_google_ads_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteGoogleAdsLinkRequest, + dict, +]) +def test_delete_google_ads_link_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/googleAdsLinks/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_google_ads_link(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_google_ads_link_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_google_ads_link in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_google_ads_link] = mock_rpc + + request = {} + client.delete_google_ads_link(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_google_ads_link(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_google_ads_link_rest_required_fields(request_type=analytics_admin.DeleteGoogleAdsLinkRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_ads_link._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_google_ads_link._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 = AnalyticsAdminServiceClient( + 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_google_ads_link(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_google_ads_link_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_google_ads_link._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_google_ads_link_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_google_ads_link") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteGoogleAdsLinkRequest.pb(analytics_admin.DeleteGoogleAdsLinkRequest()) + 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 = analytics_admin.DeleteGoogleAdsLinkRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_google_ads_link(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_google_ads_link_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteGoogleAdsLinkRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/googleAdsLinks/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_google_ads_link(request) + + +def test_delete_google_ads_link_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/googleAdsLinks/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_google_ads_link(**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/v1beta/{name=properties/*/googleAdsLinks/*}" % client.transport._host, args[1]) + + +def test_delete_google_ads_link_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_ads_link( + analytics_admin.DeleteGoogleAdsLinkRequest(), + name='name_value', + ) + + +def test_delete_google_ads_link_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListGoogleAdsLinksRequest, + dict, +]) +def test_list_google_ads_links_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListGoogleAdsLinksResponse( + 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 = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) + 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_google_ads_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGoogleAdsLinksPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_google_ads_links_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_google_ads_links in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_google_ads_links] = mock_rpc + + request = {} + client.list_google_ads_links(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_google_ads_links(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_google_ads_links_rest_required_fields(request_type=analytics_admin.ListGoogleAdsLinksRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_google_ads_links._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_google_ads_links._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListGoogleAdsLinksResponse() + # 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 = analytics_admin.ListGoogleAdsLinksResponse.pb(return_value) + 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_google_ads_links(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_google_ads_links_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_google_ads_links._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_google_ads_links_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_google_ads_links") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_google_ads_links") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListGoogleAdsLinksRequest.pb(analytics_admin.ListGoogleAdsLinksRequest()) + 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 = analytics_admin.ListGoogleAdsLinksResponse.to_json(analytics_admin.ListGoogleAdsLinksResponse()) + + request = analytics_admin.ListGoogleAdsLinksRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListGoogleAdsLinksResponse() + + client.list_google_ads_links(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_google_ads_links_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListGoogleAdsLinksRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_google_ads_links(request) + + +def test_list_google_ads_links_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListGoogleAdsLinksResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListGoogleAdsLinksResponse.pb(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_google_ads_links(**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/v1beta/{parent=properties/*}/googleAdsLinks" % client.transport._host, args[1]) + + +def test_list_google_ads_links_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_google_ads_links( + analytics_admin.ListGoogleAdsLinksRequest(), + parent='parent_value', + ) + + +def test_list_google_ads_links_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + next_page_token='abc', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[], + next_page_token='def', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + ], + next_page_token='ghi', + ), + analytics_admin.ListGoogleAdsLinksResponse( + google_ads_links=[ + resources.GoogleAdsLink(), + resources.GoogleAdsLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListGoogleAdsLinksResponse.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': 'properties/sample1'} + + pager = client.list_google_ads_links(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.GoogleAdsLink) + for i in results) + + pages = list(client.list_google_ads_links(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", [ + analytics_admin.GetDataSharingSettingsRequest, + dict, +]) +def test_get_data_sharing_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSharingSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataSharingSettings( + name='name_value', + sharing_with_google_support_enabled=True, + sharing_with_google_assigned_sales_enabled=True, + sharing_with_google_any_sales_enabled=True, + sharing_with_google_products_enabled=True, + sharing_with_others_enabled=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 = resources.DataSharingSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_sharing_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataSharingSettings) + assert response.name == 'name_value' + assert response.sharing_with_google_support_enabled is True + assert response.sharing_with_google_assigned_sales_enabled is True + assert response.sharing_with_google_any_sales_enabled is True + assert response.sharing_with_google_products_enabled is True + assert response.sharing_with_others_enabled is True + +def test_get_data_sharing_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_sharing_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_sharing_settings] = mock_rpc + + request = {} + client.get_data_sharing_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_sharing_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_sharing_settings_rest_required_fields(request_type=analytics_admin.GetDataSharingSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_sharing_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_sharing_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataSharingSettings() + # 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 = resources.DataSharingSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_sharing_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_sharing_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_sharing_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_sharing_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_data_sharing_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_sharing_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetDataSharingSettingsRequest.pb(analytics_admin.GetDataSharingSettingsRequest()) + 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 = resources.DataSharingSettings.to_json(resources.DataSharingSettings()) + + request = analytics_admin.GetDataSharingSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataSharingSettings() + + client.get_data_sharing_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_sharing_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetDataSharingSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'accounts/sample1/dataSharingSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_data_sharing_settings(request) + + +def test_get_data_sharing_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataSharingSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'accounts/sample1/dataSharingSettings'} + + # 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 = resources.DataSharingSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_sharing_settings(**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/v1beta/{name=accounts/*/dataSharingSettings}" % client.transport._host, args[1]) + + +def test_get_data_sharing_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_sharing_settings( + analytics_admin.GetDataSharingSettingsRequest(), + name='name_value', + ) + + +def test_get_data_sharing_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetMeasurementProtocolSecretRequest, + dict, +]) +def test_get_measurement_protocol_secret_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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 = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + +def test_get_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_measurement_protocol_secret] = mock_rpc + + request = {} + client.get_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_measurement_protocol_secret_rest_required_fields(request_type=analytics_admin.GetMeasurementProtocolSecretRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secret._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_measurement_protocol_secret._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.MeasurementProtocolSecret() + # 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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_measurement_protocol_secret_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_measurement_protocol_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_measurement_protocol_secret_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_measurement_protocol_secret") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_measurement_protocol_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetMeasurementProtocolSecretRequest.pb(analytics_admin.GetMeasurementProtocolSecretRequest()) + 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 = resources.MeasurementProtocolSecret.to_json(resources.MeasurementProtocolSecret()) + + request = analytics_admin.GetMeasurementProtocolSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.MeasurementProtocolSecret() + + client.get_measurement_protocol_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_measurement_protocol_secret_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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_measurement_protocol_secret(request) + + +def test_get_measurement_protocol_secret_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.MeasurementProtocolSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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 = resources.MeasurementProtocolSecret.pb(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_measurement_protocol_secret(**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/v1beta/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" % client.transport._host, args[1]) + + +def test_get_measurement_protocol_secret_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret( + analytics_admin.GetMeasurementProtocolSecretRequest(), + name='name_value', + ) + + +def test_get_measurement_protocol_secret_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListMeasurementProtocolSecretsRequest, + dict, +]) +def test_list_measurement_protocol_secrets_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListMeasurementProtocolSecretsResponse( + 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 = analytics_admin.ListMeasurementProtocolSecretsResponse.pb(return_value) + 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_measurement_protocol_secrets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListMeasurementProtocolSecretsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_measurement_protocol_secrets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_measurement_protocol_secrets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_measurement_protocol_secrets] = mock_rpc + + request = {} + client.list_measurement_protocol_secrets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_measurement_protocol_secrets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_measurement_protocol_secrets_rest_required_fields(request_type=analytics_admin.ListMeasurementProtocolSecretsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secrets._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_measurement_protocol_secrets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + # 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 = analytics_admin.ListMeasurementProtocolSecretsResponse.pb(return_value) + 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_measurement_protocol_secrets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_measurement_protocol_secrets_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_measurement_protocol_secrets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_measurement_protocol_secrets_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_measurement_protocol_secrets") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_measurement_protocol_secrets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListMeasurementProtocolSecretsRequest.pb(analytics_admin.ListMeasurementProtocolSecretsRequest()) + 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 = analytics_admin.ListMeasurementProtocolSecretsResponse.to_json(analytics_admin.ListMeasurementProtocolSecretsResponse()) + + request = analytics_admin.ListMeasurementProtocolSecretsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListMeasurementProtocolSecretsResponse() + + client.list_measurement_protocol_secrets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_measurement_protocol_secrets_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListMeasurementProtocolSecretsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_measurement_protocol_secrets(request) + + +def test_list_measurement_protocol_secrets_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListMeasurementProtocolSecretsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/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 = analytics_admin.ListMeasurementProtocolSecretsResponse.pb(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_measurement_protocol_secrets(**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/v1beta/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets" % client.transport._host, args[1]) + + +def test_list_measurement_protocol_secrets_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secrets( + analytics_admin.ListMeasurementProtocolSecretsRequest(), + parent='parent_value', + ) + + +def test_list_measurement_protocol_secrets_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + next_page_token='abc', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[], + next_page_token='def', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + ], + next_page_token='ghi', + ), + analytics_admin.ListMeasurementProtocolSecretsResponse( + measurement_protocol_secrets=[ + resources.MeasurementProtocolSecret(), + resources.MeasurementProtocolSecret(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListMeasurementProtocolSecretsResponse.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': 'properties/sample1/dataStreams/sample2'} + + pager = client.list_measurement_protocol_secrets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.MeasurementProtocolSecret) + for i in results) + + pages = list(client.list_measurement_protocol_secrets(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", [ + analytics_admin.CreateMeasurementProtocolSecretRequest, + dict, +]) +def test_create_measurement_protocol_secret_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/sample2'} + request_init["measurement_protocol_secret"] = {'name': 'name_value', 'display_name': 'display_name_value', 'secret_value': 'secret_value_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 = analytics_admin.CreateMeasurementProtocolSecretRequest.meta.fields["measurement_protocol_secret"] + + 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["measurement_protocol_secret"].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["measurement_protocol_secret"][field])): + del request_init["measurement_protocol_secret"][field][i][subfield] + else: + del request_init["measurement_protocol_secret"][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 = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + +def test_create_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_measurement_protocol_secret] = mock_rpc + + request = {} + client.create_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_measurement_protocol_secret_rest_required_fields(request_type=analytics_admin.CreateMeasurementProtocolSecretRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secret._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_measurement_protocol_secret._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.MeasurementProtocolSecret() + # 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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_measurement_protocol_secret_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_measurement_protocol_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "measurementProtocolSecret", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_measurement_protocol_secret_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_measurement_protocol_secret") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_measurement_protocol_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateMeasurementProtocolSecretRequest.pb(analytics_admin.CreateMeasurementProtocolSecretRequest()) + 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 = resources.MeasurementProtocolSecret.to_json(resources.MeasurementProtocolSecret()) + + request = analytics_admin.CreateMeasurementProtocolSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.MeasurementProtocolSecret() + + client.create_measurement_protocol_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_measurement_protocol_secret_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1/dataStreams/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_measurement_protocol_secret(request) + + +def test_create_measurement_protocol_secret_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.MeasurementProtocolSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1/dataStreams/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(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 = resources.MeasurementProtocolSecret.pb(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_measurement_protocol_secret(**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/v1beta/{parent=properties/*/dataStreams/*}/measurementProtocolSecrets" % client.transport._host, args[1]) + + +def test_create_measurement_protocol_secret_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret( + analytics_admin.CreateMeasurementProtocolSecretRequest(), + parent='parent_value', + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + ) + + +def test_create_measurement_protocol_secret_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteMeasurementProtocolSecretRequest, + dict, +]) +def test_delete_measurement_protocol_secret_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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_measurement_protocol_secret(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_measurement_protocol_secret] = mock_rpc + + request = {} + client.delete_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_measurement_protocol_secret_rest_required_fields(request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secret._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_measurement_protocol_secret._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 = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_measurement_protocol_secret_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_measurement_protocol_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_measurement_protocol_secret_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_measurement_protocol_secret") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteMeasurementProtocolSecretRequest.pb(analytics_admin.DeleteMeasurementProtocolSecretRequest()) + 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 = analytics_admin.DeleteMeasurementProtocolSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_measurement_protocol_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_measurement_protocol_secret_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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_measurement_protocol_secret(request) + + +def test_delete_measurement_protocol_secret_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/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_measurement_protocol_secret(**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/v1beta/{name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" % client.transport._host, args[1]) + + +def test_delete_measurement_protocol_secret_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret( + analytics_admin.DeleteMeasurementProtocolSecretRequest(), + name='name_value', + ) + + +def test_delete_measurement_protocol_secret_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateMeasurementProtocolSecretRequest, + dict, +]) +def test_update_measurement_protocol_secret_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'measurement_protocol_secret': {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3'}} + request_init["measurement_protocol_secret"] = {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3', 'display_name': 'display_name_value', 'secret_value': 'secret_value_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 = analytics_admin.UpdateMeasurementProtocolSecretRequest.meta.fields["measurement_protocol_secret"] + + 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["measurement_protocol_secret"].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["measurement_protocol_secret"][field])): + del request_init["measurement_protocol_secret"][field][i][subfield] + else: + del request_init["measurement_protocol_secret"][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 = resources.MeasurementProtocolSecret( + name='name_value', + display_name='display_name_value', + secret_value='secret_value_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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.MeasurementProtocolSecret) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.secret_value == 'secret_value_value' + +def test_update_measurement_protocol_secret_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_measurement_protocol_secret in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_measurement_protocol_secret] = mock_rpc + + request = {} + client.update_measurement_protocol_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_measurement_protocol_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_measurement_protocol_secret_rest_required_fields(request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_measurement_protocol_secret._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_measurement_protocol_secret._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.MeasurementProtocolSecret() + # 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 = resources.MeasurementProtocolSecret.pb(return_value) + 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_measurement_protocol_secret(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_measurement_protocol_secret_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_measurement_protocol_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("measurementProtocolSecret", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_measurement_protocol_secret_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_measurement_protocol_secret") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_measurement_protocol_secret") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateMeasurementProtocolSecretRequest.pb(analytics_admin.UpdateMeasurementProtocolSecretRequest()) + 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 = resources.MeasurementProtocolSecret.to_json(resources.MeasurementProtocolSecret()) + + request = analytics_admin.UpdateMeasurementProtocolSecretRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.MeasurementProtocolSecret() + + client.update_measurement_protocol_secret(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_measurement_protocol_secret_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateMeasurementProtocolSecretRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'measurement_protocol_secret': {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_measurement_protocol_secret(request) + + +def test_update_measurement_protocol_secret_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.MeasurementProtocolSecret() + + # get arguments that satisfy an http rule for this method + sample_request = {'measurement_protocol_secret': {'name': 'properties/sample1/dataStreams/sample2/measurementProtocolSecrets/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + measurement_protocol_secret=resources.MeasurementProtocolSecret(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 = resources.MeasurementProtocolSecret.pb(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_measurement_protocol_secret(**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/v1beta/{measurement_protocol_secret.name=properties/*/dataStreams/*/measurementProtocolSecrets/*}" % client.transport._host, args[1]) + + +def test_update_measurement_protocol_secret_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_measurement_protocol_secret( + analytics_admin.UpdateMeasurementProtocolSecretRequest(), + measurement_protocol_secret=resources.MeasurementProtocolSecret(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_measurement_protocol_secret_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.AcknowledgeUserDataCollectionRequest, + dict, +]) +def test_acknowledge_user_data_collection_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'property': 'properties/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 = analytics_admin.AcknowledgeUserDataCollectionResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.AcknowledgeUserDataCollectionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.acknowledge_user_data_collection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.AcknowledgeUserDataCollectionResponse) + +def test_acknowledge_user_data_collection_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.acknowledge_user_data_collection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.acknowledge_user_data_collection] = mock_rpc + + request = {} + client.acknowledge_user_data_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.acknowledge_user_data_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_acknowledge_user_data_collection_rest_required_fields(request_type=analytics_admin.AcknowledgeUserDataCollectionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["property"] = "" + request_init["acknowledgement"] = "" + 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()).acknowledge_user_data_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["property"] = 'property_value' + jsonified_request["acknowledgement"] = 'acknowledgement_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).acknowledge_user_data_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "property" in jsonified_request + assert jsonified_request["property"] == 'property_value' + assert "acknowledgement" in jsonified_request + assert jsonified_request["acknowledgement"] == 'acknowledgement_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() + # 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 = analytics_admin.AcknowledgeUserDataCollectionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.acknowledge_user_data_collection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_acknowledge_user_data_collection_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.acknowledge_user_data_collection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("property", "acknowledgement", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_acknowledge_user_data_collection_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_acknowledge_user_data_collection") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_acknowledge_user_data_collection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.AcknowledgeUserDataCollectionRequest.pb(analytics_admin.AcknowledgeUserDataCollectionRequest()) + 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 = analytics_admin.AcknowledgeUserDataCollectionResponse.to_json(analytics_admin.AcknowledgeUserDataCollectionResponse()) + + request = analytics_admin.AcknowledgeUserDataCollectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.AcknowledgeUserDataCollectionResponse() + + client.acknowledge_user_data_collection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_acknowledge_user_data_collection_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.AcknowledgeUserDataCollectionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'property': 'properties/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.acknowledge_user_data_collection(request) + + +def test_acknowledge_user_data_collection_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.SearchChangeHistoryEventsRequest, + dict, +]) +def test_search_change_history_events_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'account': 'accounts/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 = analytics_admin.SearchChangeHistoryEventsResponse( + 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 = analytics_admin.SearchChangeHistoryEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_change_history_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchChangeHistoryEventsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_search_change_history_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_change_history_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.search_change_history_events] = mock_rpc + + request = {} + client.search_change_history_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_change_history_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_search_change_history_events_rest_required_fields(request_type=analytics_admin.SearchChangeHistoryEventsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["account"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_change_history_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["account"] = 'account_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_change_history_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "account" in jsonified_request + assert jsonified_request["account"] == 'account_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.SearchChangeHistoryEventsResponse() + # 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 = analytics_admin.SearchChangeHistoryEventsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search_change_history_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_change_history_events_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_change_history_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("account", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_change_history_events_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_search_change_history_events") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_search_change_history_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.SearchChangeHistoryEventsRequest.pb(analytics_admin.SearchChangeHistoryEventsRequest()) + 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 = analytics_admin.SearchChangeHistoryEventsResponse.to_json(analytics_admin.SearchChangeHistoryEventsResponse()) + + request = analytics_admin.SearchChangeHistoryEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.SearchChangeHistoryEventsResponse() + + client.search_change_history_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_change_history_events_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.SearchChangeHistoryEventsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'account': 'accounts/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.search_change_history_events(request) + + +def test_search_change_history_events_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + next_page_token='abc', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[], + next_page_token='def', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.SearchChangeHistoryEventsResponse( + change_history_events=[ + resources.ChangeHistoryEvent(), + resources.ChangeHistoryEvent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.SearchChangeHistoryEventsResponse.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 = {'account': 'accounts/sample1'} + + pager = client.search_change_history_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ChangeHistoryEvent) + for i in results) + + pages = list(client.search_change_history_events(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateConversionEventRequest, + dict, +]) +def test_create_conversion_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["conversion_event"] = {'name': 'name_value', 'event_name': 'event_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'deletable': True, 'custom': True, 'counting_method': 1, 'default_conversion_value': {'value': 0.541, 'currency_code': 'currency_code_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 = analytics_admin.CreateConversionEventRequest.meta.fields["conversion_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["conversion_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["conversion_event"][field])): + del request_init["conversion_event"][field][i][subfield] + else: + del request_init["conversion_event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + +def test_create_conversion_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_conversion_event] = mock_rpc + + request = {} + client.create_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_conversion_event_rest_required_fields(request_type=analytics_admin.CreateConversionEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_event._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_conversion_event._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent() + # 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 = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_conversion_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("conversionEvent", "parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_conversion_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_conversion_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_conversion_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateConversionEventRequest.pb(analytics_admin.CreateConversionEventRequest()) + 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 = resources.ConversionEvent.to_json(resources.ConversionEvent()) + + request = analytics_admin.CreateConversionEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ConversionEvent() + + client.create_conversion_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_conversion_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateConversionEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_conversion_event(request) + + +def test_create_conversion_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.ConversionEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + conversion_event=resources.ConversionEvent(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 = resources.ConversionEvent.pb(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_conversion_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=properties/*}/conversionEvents" % client.transport._host, args[1]) + + +def test_create_conversion_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_event( + analytics_admin.CreateConversionEventRequest(), + parent='parent_value', + conversion_event=resources.ConversionEvent(name='name_value'), + ) + + +def test_create_conversion_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateConversionEventRequest, + dict, +]) +def test_update_conversion_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'conversion_event': {'name': 'properties/sample1/conversionEvents/sample2'}} + request_init["conversion_event"] = {'name': 'properties/sample1/conversionEvents/sample2', 'event_name': 'event_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'deletable': True, 'custom': True, 'counting_method': 1, 'default_conversion_value': {'value': 0.541, 'currency_code': 'currency_code_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 = analytics_admin.UpdateConversionEventRequest.meta.fields["conversion_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["conversion_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["conversion_event"][field])): + del request_init["conversion_event"][field][i][subfield] + else: + del request_init["conversion_event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + +def test_update_conversion_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_conversion_event] = mock_rpc + + request = {} + client.update_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_conversion_event_rest_required_fields(request_type=analytics_admin.UpdateConversionEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_conversion_event._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent() + # 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 = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_conversion_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("conversionEvent", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_conversion_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_conversion_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_conversion_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateConversionEventRequest.pb(analytics_admin.UpdateConversionEventRequest()) + 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 = resources.ConversionEvent.to_json(resources.ConversionEvent()) + + request = analytics_admin.UpdateConversionEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ConversionEvent() + + client.update_conversion_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_conversion_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateConversionEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'conversion_event': {'name': 'properties/sample1/conversionEvents/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_conversion_event(request) + + +def test_update_conversion_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.ConversionEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'conversion_event': {'name': 'properties/sample1/conversionEvents/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + conversion_event=resources.ConversionEvent(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 = resources.ConversionEvent.pb(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_conversion_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{conversion_event.name=properties/*/conversionEvents/*}" % client.transport._host, args[1]) + + +def test_update_conversion_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_event( + analytics_admin.UpdateConversionEventRequest(), + conversion_event=resources.ConversionEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_conversion_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetConversionEventRequest, + dict, +]) +def test_get_conversion_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/conversionEvents/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 = resources.ConversionEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConversionEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.ConversionEvent.ConversionCountingMethod.ONCE_PER_EVENT + +def test_get_conversion_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_conversion_event] = mock_rpc + + request = {} + client.get_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_conversion_event_rest_required_fields(request_type=analytics_admin.GetConversionEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ConversionEvent() + # 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 = resources.ConversionEvent.pb(return_value) + 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_conversion_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_conversion_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_conversion_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_conversion_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_conversion_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetConversionEventRequest.pb(analytics_admin.GetConversionEventRequest()) + 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 = resources.ConversionEvent.to_json(resources.ConversionEvent()) + + request = analytics_admin.GetConversionEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ConversionEvent() + + client.get_conversion_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_conversion_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetConversionEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/conversionEvents/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_conversion_event(request) + + +def test_get_conversion_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.ConversionEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/conversionEvents/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 = resources.ConversionEvent.pb(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_conversion_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=properties/*/conversionEvents/*}" % client.transport._host, args[1]) + + +def test_get_conversion_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_event( + analytics_admin.GetConversionEventRequest(), + name='name_value', + ) + + +def test_get_conversion_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteConversionEventRequest, + dict, +]) +def test_delete_conversion_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/conversionEvents/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_conversion_event(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_conversion_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_conversion_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_conversion_event] = mock_rpc + + request = {} + client.delete_conversion_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_conversion_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_conversion_event_rest_required_fields(request_type=analytics_admin.DeleteConversionEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_conversion_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + 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_conversion_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_conversion_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_conversion_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_conversion_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_conversion_event") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteConversionEventRequest.pb(analytics_admin.DeleteConversionEventRequest()) + 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 = analytics_admin.DeleteConversionEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_conversion_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_conversion_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteConversionEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/conversionEvents/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_conversion_event(request) + + +def test_delete_conversion_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/conversionEvents/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_conversion_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=properties/*/conversionEvents/*}" % client.transport._host, args[1]) + + +def test_delete_conversion_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_event( + analytics_admin.DeleteConversionEventRequest(), + name='name_value', + ) + + +def test_delete_conversion_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListConversionEventsRequest, + dict, +]) +def test_list_conversion_events_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListConversionEventsResponse( + 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 = analytics_admin.ListConversionEventsResponse.pb(return_value) + 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_conversion_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversionEventsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_conversion_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_conversion_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_conversion_events] = mock_rpc + + request = {} + client.list_conversion_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conversion_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_conversion_events_rest_required_fields(request_type=analytics_admin.ListConversionEventsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_conversion_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_conversion_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListConversionEventsResponse() + # 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 = analytics_admin.ListConversionEventsResponse.pb(return_value) + 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_conversion_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_conversion_events_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_conversion_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_conversion_events_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_conversion_events") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_conversion_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListConversionEventsRequest.pb(analytics_admin.ListConversionEventsRequest()) + 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 = analytics_admin.ListConversionEventsResponse.to_json(analytics_admin.ListConversionEventsResponse()) + + request = analytics_admin.ListConversionEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListConversionEventsResponse() + + client.list_conversion_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_conversion_events_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListConversionEventsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_conversion_events(request) + + +def test_list_conversion_events_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListConversionEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListConversionEventsResponse.pb(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_conversion_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=properties/*}/conversionEvents" % client.transport._host, args[1]) + + +def test_list_conversion_events_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_conversion_events( + analytics_admin.ListConversionEventsRequest(), + parent='parent_value', + ) + + +def test_list_conversion_events_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[], + next_page_token='def', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListConversionEventsResponse( + conversion_events=[ + resources.ConversionEvent(), + resources.ConversionEvent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListConversionEventsResponse.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': 'properties/sample1'} + + pager = client.list_conversion_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ConversionEvent) + for i in results) + + pages = list(client.list_conversion_events(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateKeyEventRequest, + dict, +]) +def test_create_key_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["key_event"] = {'name': 'name_value', 'event_name': 'event_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'deletable': True, 'custom': True, 'counting_method': 1, 'default_value': {'numeric_value': 0.1391, 'currency_code': 'currency_code_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 = analytics_admin.CreateKeyEventRequest.meta.fields["key_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["key_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["key_event"][field])): + del request_init["key_event"][field][i][subfield] + else: + del request_init["key_event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + +def test_create_key_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_key_event] = mock_rpc + + request = {} + client.create_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_key_event_rest_required_fields(request_type=analytics_admin.CreateKeyEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_event._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_key_event._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent() + # 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 = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_key_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("keyEvent", "parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_key_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_key_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_key_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateKeyEventRequest.pb(analytics_admin.CreateKeyEventRequest()) + 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 = resources.KeyEvent.to_json(resources.KeyEvent()) + + request = analytics_admin.CreateKeyEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyEvent() + + client.create_key_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_key_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateKeyEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_key_event(request) + + +def test_create_key_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.KeyEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + key_event=resources.KeyEvent(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 = resources.KeyEvent.pb(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_key_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=properties/*}/keyEvents" % client.transport._host, args[1]) + + +def test_create_key_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_event( + analytics_admin.CreateKeyEventRequest(), + parent='parent_value', + key_event=resources.KeyEvent(name='name_value'), + ) + + +def test_create_key_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateKeyEventRequest, + dict, +]) +def test_update_key_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'key_event': {'name': 'properties/sample1/keyEvents/sample2'}} + request_init["key_event"] = {'name': 'properties/sample1/keyEvents/sample2', 'event_name': 'event_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'deletable': True, 'custom': True, 'counting_method': 1, 'default_value': {'numeric_value': 0.1391, 'currency_code': 'currency_code_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 = analytics_admin.UpdateKeyEventRequest.meta.fields["key_event"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["key_event"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["key_event"][field])): + del request_init["key_event"][field][i][subfield] + else: + del request_init["key_event"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + +def test_update_key_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_key_event] = mock_rpc + + request = {} + client.update_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_key_event_rest_required_fields(request_type=analytics_admin.UpdateKeyEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_key_event._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent() + # 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 = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_key_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("keyEvent", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_key_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_key_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_key_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateKeyEventRequest.pb(analytics_admin.UpdateKeyEventRequest()) + 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 = resources.KeyEvent.to_json(resources.KeyEvent()) + + request = analytics_admin.UpdateKeyEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyEvent() + + client.update_key_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_key_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateKeyEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'key_event': {'name': 'properties/sample1/keyEvents/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_key_event(request) + + +def test_update_key_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.KeyEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'key_event': {'name': 'properties/sample1/keyEvents/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + key_event=resources.KeyEvent(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 = resources.KeyEvent.pb(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_key_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{key_event.name=properties/*/keyEvents/*}" % client.transport._host, args[1]) + + +def test_update_key_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_event( + analytics_admin.UpdateKeyEventRequest(), + key_event=resources.KeyEvent(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_key_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetKeyEventRequest, + dict, +]) +def test_get_key_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/keyEvents/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 = resources.KeyEvent( + name='name_value', + event_name='event_name_value', + deletable=True, + custom=True, + counting_method=resources.KeyEvent.CountingMethod.ONCE_PER_EVENT, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyEvent) + assert response.name == 'name_value' + assert response.event_name == 'event_name_value' + assert response.deletable is True + assert response.custom is True + assert response.counting_method == resources.KeyEvent.CountingMethod.ONCE_PER_EVENT + +def test_get_key_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_key_event] = mock_rpc + + request = {} + client.get_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_key_event_rest_required_fields(request_type=analytics_admin.GetKeyEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyEvent() + # 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 = resources.KeyEvent.pb(return_value) + 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_key_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_key_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_key_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_key_event") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_key_event") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetKeyEventRequest.pb(analytics_admin.GetKeyEventRequest()) + 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 = resources.KeyEvent.to_json(resources.KeyEvent()) + + request = analytics_admin.GetKeyEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyEvent() + + client.get_key_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_key_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetKeyEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/keyEvents/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_key_event(request) + + +def test_get_key_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.KeyEvent() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/keyEvents/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 = resources.KeyEvent.pb(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_key_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=properties/*/keyEvents/*}" % client.transport._host, args[1]) + + +def test_get_key_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_event( + analytics_admin.GetKeyEventRequest(), + name='name_value', + ) + + +def test_get_key_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteKeyEventRequest, + dict, +]) +def test_delete_key_event_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/keyEvents/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_key_event(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_key_event_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_key_event in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_key_event] = mock_rpc + + request = {} + client.delete_key_event(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_key_event(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_key_event_rest_required_fields(request_type=analytics_admin.DeleteKeyEventRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_key_event._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + 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_key_event(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_key_event_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_key_event._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_key_event_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_key_event") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteKeyEventRequest.pb(analytics_admin.DeleteKeyEventRequest()) + 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 = analytics_admin.DeleteKeyEventRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_key_event(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_key_event_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteKeyEventRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/keyEvents/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_key_event(request) + + +def test_delete_key_event_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/keyEvents/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_key_event(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=properties/*/keyEvents/*}" % client.transport._host, args[1]) + + +def test_delete_key_event_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_event( + analytics_admin.DeleteKeyEventRequest(), + name='name_value', + ) + + +def test_delete_key_event_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListKeyEventsRequest, + dict, +]) +def test_list_key_events_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListKeyEventsResponse( + 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 = analytics_admin.ListKeyEventsResponse.pb(return_value) + 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_key_events(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyEventsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_key_events_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_key_events in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_key_events] = mock_rpc + + request = {} + client.list_key_events(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_key_events(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_key_events_rest_required_fields(request_type=analytics_admin.ListKeyEventsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_key_events._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_events._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListKeyEventsResponse() + # 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 = analytics_admin.ListKeyEventsResponse.pb(return_value) + 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_key_events(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_key_events_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_key_events._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_key_events_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_key_events") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_key_events") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListKeyEventsRequest.pb(analytics_admin.ListKeyEventsRequest()) + 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 = analytics_admin.ListKeyEventsResponse.to_json(analytics_admin.ListKeyEventsResponse()) + + request = analytics_admin.ListKeyEventsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListKeyEventsResponse() + + client.list_key_events(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_key_events_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListKeyEventsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_key_events(request) + + +def test_list_key_events_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListKeyEventsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListKeyEventsResponse.pb(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_key_events(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=properties/*}/keyEvents" % client.transport._host, args[1]) + + +def test_list_key_events_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_key_events( + analytics_admin.ListKeyEventsRequest(), + parent='parent_value', + ) + + +def test_list_key_events_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + resources.KeyEvent(), + ], + next_page_token='abc', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[], + next_page_token='def', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + ], + next_page_token='ghi', + ), + analytics_admin.ListKeyEventsResponse( + key_events=[ + resources.KeyEvent(), + resources.KeyEvent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListKeyEventsResponse.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': 'properties/sample1'} + + pager = client.list_key_events(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.KeyEvent) + for i in results) + + pages = list(client.list_key_events(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateCustomDimensionRequest, + dict, +]) +def test_create_custom_dimension_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["custom_dimension"] = {'name': 'name_value', 'parameter_name': 'parameter_name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'scope': 1, 'disallow_ads_personalization': 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 = analytics_admin.CreateCustomDimensionRequest.meta.fields["custom_dimension"] + + 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["custom_dimension"].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["custom_dimension"][field])): + del request_init["custom_dimension"][field][i][subfield] + else: + del request_init["custom_dimension"][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 = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + +def test_create_custom_dimension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_custom_dimension] = mock_rpc + + request = {} + client.create_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_custom_dimension_rest_required_fields(request_type=analytics_admin.CreateCustomDimensionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_dimension._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_custom_dimension._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomDimension() + # 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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_custom_dimension_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "customDimension", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_custom_dimension_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_custom_dimension") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_custom_dimension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateCustomDimensionRequest.pb(analytics_admin.CreateCustomDimensionRequest()) + 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 = resources.CustomDimension.to_json(resources.CustomDimension()) + + request = analytics_admin.CreateCustomDimensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomDimension() + + client.create_custom_dimension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_custom_dimension_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateCustomDimensionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_custom_dimension(request) + + +def test_create_custom_dimension_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomDimension() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + custom_dimension=resources.CustomDimension(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 = resources.CustomDimension.pb(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_custom_dimension(**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/v1beta/{parent=properties/*}/customDimensions" % client.transport._host, args[1]) + + +def test_create_custom_dimension_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_dimension( + analytics_admin.CreateCustomDimensionRequest(), + parent='parent_value', + custom_dimension=resources.CustomDimension(name='name_value'), + ) + + +def test_create_custom_dimension_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateCustomDimensionRequest, + dict, +]) +def test_update_custom_dimension_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'custom_dimension': {'name': 'properties/sample1/customDimensions/sample2'}} + request_init["custom_dimension"] = {'name': 'properties/sample1/customDimensions/sample2', 'parameter_name': 'parameter_name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'scope': 1, 'disallow_ads_personalization': 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 = analytics_admin.UpdateCustomDimensionRequest.meta.fields["custom_dimension"] + + 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["custom_dimension"].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["custom_dimension"][field])): + del request_init["custom_dimension"][field][i][subfield] + else: + del request_init["custom_dimension"][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 = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + +def test_update_custom_dimension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_custom_dimension] = mock_rpc + + request = {} + client.update_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_custom_dimension_rest_required_fields(request_type=analytics_admin.UpdateCustomDimensionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_dimension._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_custom_dimension._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomDimension() + # 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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_custom_dimension_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_custom_dimension_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_custom_dimension") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_custom_dimension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateCustomDimensionRequest.pb(analytics_admin.UpdateCustomDimensionRequest()) + 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 = resources.CustomDimension.to_json(resources.CustomDimension()) + + request = analytics_admin.UpdateCustomDimensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomDimension() + + client.update_custom_dimension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_custom_dimension_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateCustomDimensionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'custom_dimension': {'name': 'properties/sample1/customDimensions/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_custom_dimension(request) + + +def test_update_custom_dimension_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomDimension() + + # get arguments that satisfy an http rule for this method + sample_request = {'custom_dimension': {'name': 'properties/sample1/customDimensions/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + custom_dimension=resources.CustomDimension(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 = resources.CustomDimension.pb(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_custom_dimension(**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/v1beta/{custom_dimension.name=properties/*/customDimensions/*}" % client.transport._host, args[1]) + + +def test_update_custom_dimension_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_dimension( + analytics_admin.UpdateCustomDimensionRequest(), + custom_dimension=resources.CustomDimension(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_custom_dimension_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCustomDimensionsRequest, + dict, +]) +def test_list_custom_dimensions_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListCustomDimensionsResponse( + 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 = analytics_admin.ListCustomDimensionsResponse.pb(return_value) + 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_custom_dimensions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomDimensionsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_custom_dimensions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_custom_dimensions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_custom_dimensions] = mock_rpc + + request = {} + client.list_custom_dimensions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_custom_dimensions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_custom_dimensions_rest_required_fields(request_type=analytics_admin.ListCustomDimensionsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_dimensions._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_custom_dimensions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListCustomDimensionsResponse() + # 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 = analytics_admin.ListCustomDimensionsResponse.pb(return_value) + 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_custom_dimensions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_custom_dimensions_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_custom_dimensions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_custom_dimensions_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_custom_dimensions") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_custom_dimensions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListCustomDimensionsRequest.pb(analytics_admin.ListCustomDimensionsRequest()) + 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 = analytics_admin.ListCustomDimensionsResponse.to_json(analytics_admin.ListCustomDimensionsResponse()) + + request = analytics_admin.ListCustomDimensionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListCustomDimensionsResponse() + + client.list_custom_dimensions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_custom_dimensions_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListCustomDimensionsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_custom_dimensions(request) + + +def test_list_custom_dimensions_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCustomDimensionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListCustomDimensionsResponse.pb(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_custom_dimensions(**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/v1beta/{parent=properties/*}/customDimensions" % client.transport._host, args[1]) + + +def test_list_custom_dimensions_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_dimensions( + analytics_admin.ListCustomDimensionsRequest(), + parent='parent_value', + ) + + +def test_list_custom_dimensions_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + resources.CustomDimension(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[], + next_page_token='def', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomDimensionsResponse( + custom_dimensions=[ + resources.CustomDimension(), + resources.CustomDimension(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListCustomDimensionsResponse.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': 'properties/sample1'} + + pager = client.list_custom_dimensions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomDimension) + for i in results) + + pages = list(client.list_custom_dimensions(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", [ + analytics_admin.ArchiveCustomDimensionRequest, + dict, +]) +def test_archive_custom_dimension_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customDimensions/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.archive_custom_dimension(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_archive_custom_dimension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_custom_dimension] = mock_rpc + + request = {} + client.archive_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_archive_custom_dimension_rest_required_fields(request_type=analytics_admin.ArchiveCustomDimensionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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()).archive_custom_dimension._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()).archive_custom_dimension._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 = AnalyticsAdminServiceClient( + 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': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.archive_custom_dimension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_archive_custom_dimension_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.archive_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_archive_custom_dimension_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_archive_custom_dimension") as pre: + pre.assert_not_called() + pb_message = analytics_admin.ArchiveCustomDimensionRequest.pb(analytics_admin.ArchiveCustomDimensionRequest()) + 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 = analytics_admin.ArchiveCustomDimensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.archive_custom_dimension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_archive_custom_dimension_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ArchiveCustomDimensionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customDimensions/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.archive_custom_dimension(request) + + +def test_archive_custom_dimension_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/customDimensions/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.archive_custom_dimension(**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/v1beta/{name=properties/*/customDimensions/*}:archive" % client.transport._host, args[1]) + + +def test_archive_custom_dimension_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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.archive_custom_dimension( + analytics_admin.ArchiveCustomDimensionRequest(), + name='name_value', + ) + + +def test_archive_custom_dimension_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCustomDimensionRequest, + dict, +]) +def test_get_custom_dimension_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customDimensions/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 = resources.CustomDimension( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + scope=resources.CustomDimension.DimensionScope.EVENT, + disallow_ads_personalization=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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomDimension) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.scope == resources.CustomDimension.DimensionScope.EVENT + assert response.disallow_ads_personalization is True + +def test_get_custom_dimension_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_custom_dimension in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_custom_dimension] = mock_rpc + + request = {} + client.get_custom_dimension(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_custom_dimension(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_custom_dimension_rest_required_fields(request_type=analytics_admin.GetCustomDimensionRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_dimension._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_custom_dimension._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomDimension() + # 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 = resources.CustomDimension.pb(return_value) + 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_custom_dimension(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_custom_dimension_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_custom_dimension._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_custom_dimension_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_custom_dimension") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_custom_dimension") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetCustomDimensionRequest.pb(analytics_admin.GetCustomDimensionRequest()) + 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 = resources.CustomDimension.to_json(resources.CustomDimension()) + + request = analytics_admin.GetCustomDimensionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomDimension() + + client.get_custom_dimension(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_custom_dimension_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetCustomDimensionRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customDimensions/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_custom_dimension(request) + + +def test_get_custom_dimension_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomDimension() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/customDimensions/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 = resources.CustomDimension.pb(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_custom_dimension(**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/v1beta/{name=properties/*/customDimensions/*}" % client.transport._host, args[1]) + + +def test_get_custom_dimension_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_dimension( + analytics_admin.GetCustomDimensionRequest(), + name='name_value', + ) + + +def test_get_custom_dimension_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateCustomMetricRequest, + dict, +]) +def test_create_custom_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["custom_metric"] = {'name': 'name_value', 'parameter_name': 'parameter_name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'measurement_unit': 1, 'scope': 1, 'restricted_metric_type': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateCustomMetricRequest.meta.fields["custom_metric"] + + 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["custom_metric"].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["custom_metric"][field])): + del request_init["custom_metric"][field][i][subfield] + else: + del request_init["custom_metric"][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 = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + +def test_create_custom_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_custom_metric] = mock_rpc + + request = {} + client.create_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_custom_metric_rest_required_fields(request_type=analytics_admin.CreateCustomMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_metric._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_custom_metric._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomMetric() + # 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 = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_custom_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "customMetric", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_custom_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_custom_metric") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_custom_metric") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateCustomMetricRequest.pb(analytics_admin.CreateCustomMetricRequest()) + 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 = resources.CustomMetric.to_json(resources.CustomMetric()) + + request = analytics_admin.CreateCustomMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomMetric() + + client.create_custom_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_custom_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateCustomMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_custom_metric(request) + + +def test_create_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + custom_metric=resources.CustomMetric(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 = resources.CustomMetric.pb(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_custom_metric(**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/v1beta/{parent=properties/*}/customMetrics" % client.transport._host, args[1]) + + +def test_create_custom_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_metric( + analytics_admin.CreateCustomMetricRequest(), + parent='parent_value', + custom_metric=resources.CustomMetric(name='name_value'), + ) + + +def test_create_custom_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateCustomMetricRequest, + dict, +]) +def test_update_custom_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'custom_metric': {'name': 'properties/sample1/customMetrics/sample2'}} + request_init["custom_metric"] = {'name': 'properties/sample1/customMetrics/sample2', 'parameter_name': 'parameter_name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'measurement_unit': 1, 'scope': 1, 'restricted_metric_type': [1]} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateCustomMetricRequest.meta.fields["custom_metric"] + + 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["custom_metric"].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["custom_metric"][field])): + del request_init["custom_metric"][field][i][subfield] + else: + del request_init["custom_metric"][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 = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + +def test_update_custom_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_custom_metric] = mock_rpc + + request = {} + client.update_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_custom_metric_rest_required_fields(request_type=analytics_admin.UpdateCustomMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_metric._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_custom_metric._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomMetric() + # 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 = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_custom_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_custom_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_custom_metric") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_custom_metric") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateCustomMetricRequest.pb(analytics_admin.UpdateCustomMetricRequest()) + 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 = resources.CustomMetric.to_json(resources.CustomMetric()) + + request = analytics_admin.UpdateCustomMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomMetric() + + client.update_custom_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_custom_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateCustomMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'custom_metric': {'name': 'properties/sample1/customMetrics/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_custom_metric(request) + + +def test_update_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {'custom_metric': {'name': 'properties/sample1/customMetrics/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + custom_metric=resources.CustomMetric(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 = resources.CustomMetric.pb(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_custom_metric(**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/v1beta/{custom_metric.name=properties/*/customMetrics/*}" % client.transport._host, args[1]) + + +def test_update_custom_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_metric( + analytics_admin.UpdateCustomMetricRequest(), + custom_metric=resources.CustomMetric(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_custom_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListCustomMetricsRequest, + dict, +]) +def test_list_custom_metrics_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListCustomMetricsResponse( + 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 = analytics_admin.ListCustomMetricsResponse.pb(return_value) + 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_custom_metrics(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCustomMetricsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_custom_metrics_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_custom_metrics in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_custom_metrics] = mock_rpc + + request = {} + client.list_custom_metrics(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_custom_metrics(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_custom_metrics_rest_required_fields(request_type=analytics_admin.ListCustomMetricsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_metrics._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_custom_metrics._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListCustomMetricsResponse() + # 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 = analytics_admin.ListCustomMetricsResponse.pb(return_value) + 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_custom_metrics(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_custom_metrics_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_custom_metrics._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_custom_metrics_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_custom_metrics") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_custom_metrics") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListCustomMetricsRequest.pb(analytics_admin.ListCustomMetricsRequest()) + 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 = analytics_admin.ListCustomMetricsResponse.to_json(analytics_admin.ListCustomMetricsResponse()) + + request = analytics_admin.ListCustomMetricsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListCustomMetricsResponse() + + client.list_custom_metrics(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_custom_metrics_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListCustomMetricsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_custom_metrics(request) + + +def test_list_custom_metrics_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListCustomMetricsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListCustomMetricsResponse.pb(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_custom_metrics(**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/v1beta/{parent=properties/*}/customMetrics" % client.transport._host, args[1]) + + +def test_list_custom_metrics_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_metrics( + analytics_admin.ListCustomMetricsRequest(), + parent='parent_value', + ) + + +def test_list_custom_metrics_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + resources.CustomMetric(), + ], + next_page_token='abc', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[], + next_page_token='def', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + ], + next_page_token='ghi', + ), + analytics_admin.ListCustomMetricsResponse( + custom_metrics=[ + resources.CustomMetric(), + resources.CustomMetric(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListCustomMetricsResponse.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': 'properties/sample1'} + + pager = client.list_custom_metrics(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CustomMetric) + for i in results) + + pages = list(client.list_custom_metrics(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", [ + analytics_admin.ArchiveCustomMetricRequest, + dict, +]) +def test_archive_custom_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customMetrics/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.archive_custom_metric(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_archive_custom_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.archive_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.archive_custom_metric] = mock_rpc + + request = {} + client.archive_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.archive_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_archive_custom_metric_rest_required_fields(request_type=analytics_admin.ArchiveCustomMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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()).archive_custom_metric._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()).archive_custom_metric._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 = AnalyticsAdminServiceClient( + 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': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.archive_custom_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_archive_custom_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.archive_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_archive_custom_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_archive_custom_metric") as pre: + pre.assert_not_called() + pb_message = analytics_admin.ArchiveCustomMetricRequest.pb(analytics_admin.ArchiveCustomMetricRequest()) + 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 = analytics_admin.ArchiveCustomMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.archive_custom_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_archive_custom_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ArchiveCustomMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customMetrics/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.archive_custom_metric(request) + + +def test_archive_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/customMetrics/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.archive_custom_metric(**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/v1beta/{name=properties/*/customMetrics/*}:archive" % client.transport._host, args[1]) + + +def test_archive_custom_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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.archive_custom_metric( + analytics_admin.ArchiveCustomMetricRequest(), + name='name_value', + ) + + +def test_archive_custom_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetCustomMetricRequest, + dict, +]) +def test_get_custom_metric_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customMetrics/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 = resources.CustomMetric( + name='name_value', + parameter_name='parameter_name_value', + display_name='display_name_value', + description='description_value', + measurement_unit=resources.CustomMetric.MeasurementUnit.STANDARD, + scope=resources.CustomMetric.MetricScope.EVENT, + restricted_metric_type=[resources.CustomMetric.RestrictedMetricType.COST_DATA], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CustomMetric) + assert response.name == 'name_value' + assert response.parameter_name == 'parameter_name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.measurement_unit == resources.CustomMetric.MeasurementUnit.STANDARD + assert response.scope == resources.CustomMetric.MetricScope.EVENT + assert response.restricted_metric_type == [resources.CustomMetric.RestrictedMetricType.COST_DATA] + +def test_get_custom_metric_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_custom_metric in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_custom_metric] = mock_rpc + + request = {} + client.get_custom_metric(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_custom_metric(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_custom_metric_rest_required_fields(request_type=analytics_admin.GetCustomMetricRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + 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_custom_metric._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_custom_metric._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CustomMetric() + # 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 = resources.CustomMetric.pb(return_value) + 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_custom_metric(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_custom_metric_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_custom_metric._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_custom_metric_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_custom_metric") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_custom_metric") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetCustomMetricRequest.pb(analytics_admin.GetCustomMetricRequest()) + 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 = resources.CustomMetric.to_json(resources.CustomMetric()) + + request = analytics_admin.GetCustomMetricRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CustomMetric() + + client.get_custom_metric(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_custom_metric_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetCustomMetricRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/customMetrics/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_custom_metric(request) + + +def test_get_custom_metric_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.CustomMetric() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/customMetrics/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 = resources.CustomMetric.pb(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_custom_metric(**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/v1beta/{name=properties/*/customMetrics/*}" % client.transport._host, args[1]) + + +def test_get_custom_metric_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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_custom_metric( + analytics_admin.GetCustomMetricRequest(), + name='name_value', + ) + + +def test_get_custom_metric_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataRetentionSettingsRequest, + dict, +]) +def test_get_data_retention_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataRetentionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_retention_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + +def test_get_data_retention_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_retention_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_retention_settings] = mock_rpc + + request = {} + client.get_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_retention_settings_rest_required_fields(request_type=analytics_admin.GetDataRetentionSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_retention_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_retention_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataRetentionSettings() + # 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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_retention_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_retention_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_retention_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_retention_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_data_retention_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_retention_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetDataRetentionSettingsRequest.pb(analytics_admin.GetDataRetentionSettingsRequest()) + 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 = resources.DataRetentionSettings.to_json(resources.DataRetentionSettings()) + + request = analytics_admin.GetDataRetentionSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataRetentionSettings() + + client.get_data_retention_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_retention_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetDataRetentionSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataRetentionSettings'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_data_retention_settings(request) + + +def test_get_data_retention_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataRetentionSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataRetentionSettings'} + + # 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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_retention_settings(**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/v1beta/{name=properties/*/dataRetentionSettings}" % client.transport._host, args[1]) + + +def test_get_data_retention_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_retention_settings( + analytics_admin.GetDataRetentionSettingsRequest(), + name='name_value', + ) + + +def test_get_data_retention_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDataRetentionSettingsRequest, + dict, +]) +def test_update_data_retention_settings_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_retention_settings': {'name': 'properties/sample1/dataRetentionSettings'}} + request_init["data_retention_settings"] = {'name': 'properties/sample1/dataRetentionSettings', 'event_data_retention': 1, 'reset_user_data_on_new_activity': 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 = analytics_admin.UpdateDataRetentionSettingsRequest.meta.fields["data_retention_settings"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_retention_settings"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_retention_settings"][field])): + del request_init["data_retention_settings"][field][i][subfield] + else: + del request_init["data_retention_settings"][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 = resources.DataRetentionSettings( + name='name_value', + event_data_retention=resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS, + reset_user_data_on_new_activity=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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_data_retention_settings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataRetentionSettings) + assert response.name == 'name_value' + assert response.event_data_retention == resources.DataRetentionSettings.RetentionDuration.TWO_MONTHS + assert response.reset_user_data_on_new_activity is True + +def test_update_data_retention_settings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_retention_settings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_retention_settings] = mock_rpc + + request = {} + client.update_data_retention_settings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_retention_settings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_data_retention_settings_rest_required_fields(request_type=analytics_admin.UpdateDataRetentionSettingsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_retention_settings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_retention_settings._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataRetentionSettings() + # 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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_data_retention_settings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_data_retention_settings_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_data_retention_settings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("dataRetentionSettings", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_retention_settings_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_data_retention_settings") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_data_retention_settings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateDataRetentionSettingsRequest.pb(analytics_admin.UpdateDataRetentionSettingsRequest()) + 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 = resources.DataRetentionSettings.to_json(resources.DataRetentionSettings()) + + request = analytics_admin.UpdateDataRetentionSettingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataRetentionSettings() + + client.update_data_retention_settings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_data_retention_settings_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateDataRetentionSettingsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_retention_settings': {'name': 'properties/sample1/dataRetentionSettings'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_data_retention_settings(request) + + +def test_update_data_retention_settings_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataRetentionSettings() + + # get arguments that satisfy an http rule for this method + sample_request = {'data_retention_settings': {'name': 'properties/sample1/dataRetentionSettings'}} + + # get truthy value for each flattened field + mock_args = dict( + data_retention_settings=resources.DataRetentionSettings(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 = resources.DataRetentionSettings.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_data_retention_settings(**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/v1beta/{data_retention_settings.name=properties/*/dataRetentionSettings}" % client.transport._host, args[1]) + + +def test_update_data_retention_settings_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_retention_settings( + analytics_admin.UpdateDataRetentionSettingsRequest(), + data_retention_settings=resources.DataRetentionSettings(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_data_retention_settings_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.CreateDataStreamRequest, + dict, +]) +def test_create_data_stream_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/sample1'} + request_init["data_stream"] = {'web_stream_data': {'measurement_id': 'measurement_id_value', 'firebase_app_id': 'firebase_app_id_value', 'default_uri': 'default_uri_value'}, 'android_app_stream_data': {'firebase_app_id': 'firebase_app_id_value', 'package_name': 'package_name_value'}, 'ios_app_stream_data': {'firebase_app_id': 'firebase_app_id_value', 'bundle_id': 'bundle_id_value'}, 'name': 'name_value', 'type_': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.CreateDataStreamRequest.meta.fields["data_stream"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_stream"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_stream"][field])): + del request_init["data_stream"][field][i][subfield] + else: + del request_init["data_stream"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_data_stream(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + +def test_create_data_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_data_stream] = mock_rpc + + request = {} + client.create_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_data_stream_rest_required_fields(request_type=analytics_admin.CreateDataStreamRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_data_stream._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataStream() + # 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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_data_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_data_stream_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "dataStream", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_data_stream_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_create_data_stream") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_create_data_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.CreateDataStreamRequest.pb(analytics_admin.CreateDataStreamRequest()) + 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 = resources.DataStream.to_json(resources.DataStream()) + + request = analytics_admin.CreateDataStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataStream() + + client.create_data_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_data_stream_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.CreateDataStreamRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_data_stream(request) + + +def test_create_data_stream_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataStream() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_data_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=properties/*}/dataStreams" % client.transport._host, args[1]) + + +def test_create_data_stream_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_data_stream( + analytics_admin.CreateDataStreamRequest(), + parent='parent_value', + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + ) + + +def test_create_data_stream_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.DeleteDataStreamRequest, + dict, +]) +def test_delete_data_stream_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/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_data_stream(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_data_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.delete_data_stream] = mock_rpc + + request = {} + client.delete_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_data_stream_rest_required_fields(request_type=analytics_admin.DeleteDataStreamRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_data_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_data_stream_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_data_stream_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "pre_delete_data_stream") as pre: + pre.assert_not_called() + pb_message = analytics_admin.DeleteDataStreamRequest.pb(analytics_admin.DeleteDataStreamRequest()) + 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 = analytics_admin.DeleteDataStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_data_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_data_stream_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.DeleteDataStreamRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/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_data_stream(request) + + +def test_delete_data_stream_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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': 'properties/sample1/dataStreams/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_data_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=properties/*/dataStreams/*}" % client.transport._host, args[1]) + + +def test_delete_data_stream_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_data_stream( + analytics_admin.DeleteDataStreamRequest(), + name='name_value', + ) + + +def test_delete_data_stream_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.UpdateDataStreamRequest, + dict, +]) +def test_update_data_stream_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'data_stream': {'name': 'properties/sample1/dataStreams/sample2'}} + request_init["data_stream"] = {'web_stream_data': {'measurement_id': 'measurement_id_value', 'firebase_app_id': 'firebase_app_id_value', 'default_uri': 'default_uri_value'}, 'android_app_stream_data': {'firebase_app_id': 'firebase_app_id_value', 'package_name': 'package_name_value'}, 'ios_app_stream_data': {'firebase_app_id': 'firebase_app_id_value', 'bundle_id': 'bundle_id_value'}, 'name': 'properties/sample1/dataStreams/sample2', 'type_': 1, 'display_name': 'display_name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = analytics_admin.UpdateDataStreamRequest.meta.fields["data_stream"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["data_stream"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["data_stream"][field])): + del request_init["data_stream"][field][i][subfield] + else: + del request_init["data_stream"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_data_stream(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + +def test_update_data_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_data_stream] = mock_rpc + + request = {} + client.update_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_data_stream_rest_required_fields(request_type=analytics_admin.UpdateDataStreamRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_data_stream._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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataStream() + # 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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_data_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_data_stream_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_data_stream_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_update_data_stream") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_update_data_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.UpdateDataStreamRequest.pb(analytics_admin.UpdateDataStreamRequest()) + 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 = resources.DataStream.to_json(resources.DataStream()) + + request = analytics_admin.UpdateDataStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataStream() + + client.update_data_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_data_stream_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.UpdateDataStreamRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'data_stream': {'name': 'properties/sample1/dataStreams/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_data_stream(request) + + +def test_update_data_stream_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataStream() + + # get arguments that satisfy an http rule for this method + sample_request = {'data_stream': {'name': 'properties/sample1/dataStreams/sample2'}} + + # get truthy value for each flattened field + mock_args = dict( + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_data_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{data_stream.name=properties/*/dataStreams/*}" % client.transport._host, args[1]) + + +def test_update_data_stream_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_data_stream( + analytics_admin.UpdateDataStreamRequest(), + data_stream=resources.DataStream(web_stream_data=resources.DataStream.WebStreamData(measurement_id='measurement_id_value')), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_data_stream_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.ListDataStreamsRequest, + dict, +]) +def test_list_data_streams_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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 = analytics_admin.ListDataStreamsResponse( + 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 = analytics_admin.ListDataStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_data_streams(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataStreamsPager) + assert response.next_page_token == 'next_page_token_value' + +def test_list_data_streams_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_data_streams in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_data_streams] = mock_rpc + + request = {} + client.list_data_streams(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_streams(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_data_streams_rest_required_fields(request_type=analytics_admin.ListDataStreamsRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_streams._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_data_streams._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = analytics_admin.ListDataStreamsResponse() + # 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 = analytics_admin.ListDataStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_data_streams(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_data_streams_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_data_streams._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_data_streams_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_list_data_streams") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_list_data_streams") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.ListDataStreamsRequest.pb(analytics_admin.ListDataStreamsRequest()) + 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 = analytics_admin.ListDataStreamsResponse.to_json(analytics_admin.ListDataStreamsResponse()) + + request = analytics_admin.ListDataStreamsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.ListDataStreamsResponse() + + client.list_data_streams(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_data_streams_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.ListDataStreamsRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'properties/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_data_streams(request) + + +def test_list_data_streams_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = analytics_admin.ListDataStreamsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'properties/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 = analytics_admin.ListDataStreamsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_data_streams(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{parent=properties/*}/dataStreams" % client.transport._host, args[1]) + + +def test_list_data_streams_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_data_streams( + analytics_admin.ListDataStreamsRequest(), + parent='parent_value', + ) + + +def test_list_data_streams_rest_pager(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + 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 = ( + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + resources.DataStream(), + ], + next_page_token='abc', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[], + next_page_token='def', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + ], + next_page_token='ghi', + ), + analytics_admin.ListDataStreamsResponse( + data_streams=[ + resources.DataStream(), + resources.DataStream(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(analytics_admin.ListDataStreamsResponse.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': 'properties/sample1'} + + pager = client.list_data_streams(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.DataStream) + for i in results) + + pages = list(client.list_data_streams(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.GetDataStreamRequest, + dict, +]) +def test_get_data_stream_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/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 = resources.DataStream( + name='name_value', + type_=resources.DataStream.DataStreamType.WEB_DATA_STREAM, + display_name='display_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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_data_stream(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.DataStream) + assert response.name == 'name_value' + assert response.type_ == resources.DataStream.DataStreamType.WEB_DATA_STREAM + assert response.display_name == 'display_name_value' + +def test_get_data_stream_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_data_stream in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_data_stream] = mock_rpc + + request = {} + client.get_data_stream(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_stream(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_data_stream_rest_required_fields(request_type=analytics_admin.GetDataStreamRequest): + transport_class = transports.AnalyticsAdminServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_data_stream._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.DataStream() + # 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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_data_stream(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_data_stream_rest_unset_required_fields(): + transport = transports.AnalyticsAdminServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_data_stream._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_stream_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_get_data_stream") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_get_data_stream") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.GetDataStreamRequest.pb(analytics_admin.GetDataStreamRequest()) + 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 = resources.DataStream.to_json(resources.DataStream()) + + request = analytics_admin.GetDataStreamRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.DataStream() + + client.get_data_stream(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_data_stream_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.GetDataStreamRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'properties/sample1/dataStreams/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_data_stream(request) + + +def test_get_data_stream_rest_flattened(): + client = AnalyticsAdminServiceClient( + 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 = resources.DataStream() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'properties/sample1/dataStreams/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 = resources.DataStream.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_data_stream(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1beta/{name=properties/*/dataStreams/*}" % client.transport._host, args[1]) + + +def test_get_data_stream_rest_flattened_error(transport: str = 'rest'): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_data_stream( + analytics_admin.GetDataStreamRequest(), + name='name_value', + ) + + +def test_get_data_stream_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + analytics_admin.RunAccessReportRequest, + dict, +]) +def test_run_access_report_rest(request_type): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'entity': 'properties/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 = analytics_admin.RunAccessReportResponse( + row_count=992, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = analytics_admin.RunAccessReportResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.run_access_report(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, analytics_admin.RunAccessReportResponse) + assert response.row_count == 992 + +def test_run_access_report_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_access_report in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.run_access_report] = mock_rpc + + request = {} + client.run_access_report(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_access_report(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_access_report_rest_interceptors(null_interceptor): + transport = transports.AnalyticsAdminServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AnalyticsAdminServiceRestInterceptor(), + ) + client = AnalyticsAdminServiceClient(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.AnalyticsAdminServiceRestInterceptor, "post_run_access_report") as post, \ + mock.patch.object(transports.AnalyticsAdminServiceRestInterceptor, "pre_run_access_report") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = analytics_admin.RunAccessReportRequest.pb(analytics_admin.RunAccessReportRequest()) + 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 = analytics_admin.RunAccessReportResponse.to_json(analytics_admin.RunAccessReportResponse()) + + request = analytics_admin.RunAccessReportRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = analytics_admin.RunAccessReportResponse() + + client.run_access_report(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_run_access_report_rest_bad_request(transport: str = 'rest', request_type=analytics_admin.RunAccessReportRequest): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'entity': 'properties/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.run_access_report(request) + + +def test_run_access_report_rest_error(): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnalyticsAdminServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AnalyticsAdminServiceClient( + 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 = AnalyticsAdminServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AnalyticsAdminServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AnalyticsAdminServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AnalyticsAdminServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AnalyticsAdminServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AnalyticsAdminServiceGrpcTransport, + transports.AnalyticsAdminServiceGrpcAsyncIOTransport, + transports.AnalyticsAdminServiceRestTransport, +]) +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 = AnalyticsAdminServiceClient.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 = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AnalyticsAdminServiceGrpcTransport, + ) + +def test_analytics_admin_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AnalyticsAdminServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_analytics_admin_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.analytics.admin_v1beta.services.analytics_admin_service.transports.AnalyticsAdminServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AnalyticsAdminServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'get_account', + 'list_accounts', + 'delete_account', + 'update_account', + 'provision_account_ticket', + 'list_account_summaries', + 'get_property', + 'list_properties', + 'create_property', + 'delete_property', + 'update_property', + 'create_firebase_link', + 'delete_firebase_link', + 'list_firebase_links', + 'create_google_ads_link', + 'update_google_ads_link', + 'delete_google_ads_link', + 'list_google_ads_links', + 'get_data_sharing_settings', + 'get_measurement_protocol_secret', + 'list_measurement_protocol_secrets', + 'create_measurement_protocol_secret', + 'delete_measurement_protocol_secret', + 'update_measurement_protocol_secret', + 'acknowledge_user_data_collection', + 'search_change_history_events', + 'create_conversion_event', + 'update_conversion_event', + 'get_conversion_event', + 'delete_conversion_event', + 'list_conversion_events', + 'create_key_event', + 'update_key_event', + 'get_key_event', + 'delete_key_event', + 'list_key_events', + 'create_custom_dimension', + 'update_custom_dimension', + 'list_custom_dimensions', + 'archive_custom_dimension', + 'get_custom_dimension', + 'create_custom_metric', + 'update_custom_metric', + 'list_custom_metrics', + 'archive_custom_metric', + 'get_custom_metric', + 'get_data_retention_settings', + 'update_data_retention_settings', + 'create_data_stream', + 'delete_data_stream', + 'update_data_stream', + 'list_data_streams', + 'get_data_stream', + 'run_access_report', + ) + 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_analytics_admin_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.analytics.admin_v1beta.services.analytics_admin_service.transports.AnalyticsAdminServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnalyticsAdminServiceTransport( + 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/analytics.edit', + 'https://www.googleapis.com/auth/analytics.readonly', +), + quota_project_id="octopus", + ) + + +def test_analytics_admin_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.analytics.admin_v1beta.services.analytics_admin_service.transports.AnalyticsAdminServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AnalyticsAdminServiceTransport() + adc.assert_called_once() + + +def test_analytics_admin_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) + AnalyticsAdminServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/analytics.edit', + 'https://www.googleapis.com/auth/analytics.readonly', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnalyticsAdminServiceGrpcTransport, + transports.AnalyticsAdminServiceGrpcAsyncIOTransport, + ], +) +def test_analytics_admin_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/analytics.edit', 'https://www.googleapis.com/auth/analytics.readonly',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AnalyticsAdminServiceGrpcTransport, + transports.AnalyticsAdminServiceGrpcAsyncIOTransport, + transports.AnalyticsAdminServiceRestTransport, + ], +) +def test_analytics_admin_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.AnalyticsAdminServiceGrpcTransport, grpc_helpers), + (transports.AnalyticsAdminServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_analytics_admin_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( + "analyticsadmin.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/analytics.edit', + 'https://www.googleapis.com/auth/analytics.readonly', +), + scopes=["1", "2"], + default_host="analyticsadmin.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AnalyticsAdminServiceGrpcTransport, transports.AnalyticsAdminServiceGrpcAsyncIOTransport]) +def test_analytics_admin_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_analytics_admin_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.AnalyticsAdminServiceRestTransport ( + 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_analytics_admin_service_host_no_port(transport_name): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='analyticsadmin.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'analyticsadmin.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://analyticsadmin.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_analytics_admin_service_host_with_port(transport_name): + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='analyticsadmin.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'analyticsadmin.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://analyticsadmin.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_analytics_admin_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AnalyticsAdminServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AnalyticsAdminServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_account._session + session2 = client2.transport.get_account._session + assert session1 != session2 + session1 = client1.transport.list_accounts._session + session2 = client2.transport.list_accounts._session + assert session1 != session2 + session1 = client1.transport.delete_account._session + session2 = client2.transport.delete_account._session + assert session1 != session2 + session1 = client1.transport.update_account._session + session2 = client2.transport.update_account._session + assert session1 != session2 + session1 = client1.transport.provision_account_ticket._session + session2 = client2.transport.provision_account_ticket._session + assert session1 != session2 + session1 = client1.transport.list_account_summaries._session + session2 = client2.transport.list_account_summaries._session + assert session1 != session2 + session1 = client1.transport.get_property._session + session2 = client2.transport.get_property._session + assert session1 != session2 + session1 = client1.transport.list_properties._session + session2 = client2.transport.list_properties._session + assert session1 != session2 + session1 = client1.transport.create_property._session + session2 = client2.transport.create_property._session + assert session1 != session2 + session1 = client1.transport.delete_property._session + session2 = client2.transport.delete_property._session + assert session1 != session2 + session1 = client1.transport.update_property._session + session2 = client2.transport.update_property._session + assert session1 != session2 + session1 = client1.transport.create_firebase_link._session + session2 = client2.transport.create_firebase_link._session + assert session1 != session2 + session1 = client1.transport.delete_firebase_link._session + session2 = client2.transport.delete_firebase_link._session + assert session1 != session2 + session1 = client1.transport.list_firebase_links._session + session2 = client2.transport.list_firebase_links._session + assert session1 != session2 + session1 = client1.transport.create_google_ads_link._session + session2 = client2.transport.create_google_ads_link._session + assert session1 != session2 + session1 = client1.transport.update_google_ads_link._session + session2 = client2.transport.update_google_ads_link._session + assert session1 != session2 + session1 = client1.transport.delete_google_ads_link._session + session2 = client2.transport.delete_google_ads_link._session + assert session1 != session2 + session1 = client1.transport.list_google_ads_links._session + session2 = client2.transport.list_google_ads_links._session + assert session1 != session2 + session1 = client1.transport.get_data_sharing_settings._session + session2 = client2.transport.get_data_sharing_settings._session + assert session1 != session2 + session1 = client1.transport.get_measurement_protocol_secret._session + session2 = client2.transport.get_measurement_protocol_secret._session + assert session1 != session2 + session1 = client1.transport.list_measurement_protocol_secrets._session + session2 = client2.transport.list_measurement_protocol_secrets._session + assert session1 != session2 + session1 = client1.transport.create_measurement_protocol_secret._session + session2 = client2.transport.create_measurement_protocol_secret._session + assert session1 != session2 + session1 = client1.transport.delete_measurement_protocol_secret._session + session2 = client2.transport.delete_measurement_protocol_secret._session + assert session1 != session2 + session1 = client1.transport.update_measurement_protocol_secret._session + session2 = client2.transport.update_measurement_protocol_secret._session + assert session1 != session2 + session1 = client1.transport.acknowledge_user_data_collection._session + session2 = client2.transport.acknowledge_user_data_collection._session + assert session1 != session2 + session1 = client1.transport.search_change_history_events._session + session2 = client2.transport.search_change_history_events._session + assert session1 != session2 + session1 = client1.transport.create_conversion_event._session + session2 = client2.transport.create_conversion_event._session + assert session1 != session2 + session1 = client1.transport.update_conversion_event._session + session2 = client2.transport.update_conversion_event._session + assert session1 != session2 + session1 = client1.transport.get_conversion_event._session + session2 = client2.transport.get_conversion_event._session + assert session1 != session2 + session1 = client1.transport.delete_conversion_event._session + session2 = client2.transport.delete_conversion_event._session + assert session1 != session2 + session1 = client1.transport.list_conversion_events._session + session2 = client2.transport.list_conversion_events._session + assert session1 != session2 + session1 = client1.transport.create_key_event._session + session2 = client2.transport.create_key_event._session + assert session1 != session2 + session1 = client1.transport.update_key_event._session + session2 = client2.transport.update_key_event._session + assert session1 != session2 + session1 = client1.transport.get_key_event._session + session2 = client2.transport.get_key_event._session + assert session1 != session2 + session1 = client1.transport.delete_key_event._session + session2 = client2.transport.delete_key_event._session + assert session1 != session2 + session1 = client1.transport.list_key_events._session + session2 = client2.transport.list_key_events._session + assert session1 != session2 + session1 = client1.transport.create_custom_dimension._session + session2 = client2.transport.create_custom_dimension._session + assert session1 != session2 + session1 = client1.transport.update_custom_dimension._session + session2 = client2.transport.update_custom_dimension._session + assert session1 != session2 + session1 = client1.transport.list_custom_dimensions._session + session2 = client2.transport.list_custom_dimensions._session + assert session1 != session2 + session1 = client1.transport.archive_custom_dimension._session + session2 = client2.transport.archive_custom_dimension._session + assert session1 != session2 + session1 = client1.transport.get_custom_dimension._session + session2 = client2.transport.get_custom_dimension._session + assert session1 != session2 + session1 = client1.transport.create_custom_metric._session + session2 = client2.transport.create_custom_metric._session + assert session1 != session2 + session1 = client1.transport.update_custom_metric._session + session2 = client2.transport.update_custom_metric._session + assert session1 != session2 + session1 = client1.transport.list_custom_metrics._session + session2 = client2.transport.list_custom_metrics._session + assert session1 != session2 + session1 = client1.transport.archive_custom_metric._session + session2 = client2.transport.archive_custom_metric._session + assert session1 != session2 + session1 = client1.transport.get_custom_metric._session + session2 = client2.transport.get_custom_metric._session + assert session1 != session2 + session1 = client1.transport.get_data_retention_settings._session + session2 = client2.transport.get_data_retention_settings._session + assert session1 != session2 + session1 = client1.transport.update_data_retention_settings._session + session2 = client2.transport.update_data_retention_settings._session + assert session1 != session2 + session1 = client1.transport.create_data_stream._session + session2 = client2.transport.create_data_stream._session + assert session1 != session2 + session1 = client1.transport.delete_data_stream._session + session2 = client2.transport.delete_data_stream._session + assert session1 != session2 + session1 = client1.transport.update_data_stream._session + session2 = client2.transport.update_data_stream._session + assert session1 != session2 + session1 = client1.transport.list_data_streams._session + session2 = client2.transport.list_data_streams._session + assert session1 != session2 + session1 = client1.transport.get_data_stream._session + session2 = client2.transport.get_data_stream._session + assert session1 != session2 + session1 = client1.transport.run_access_report._session + session2 = client2.transport.run_access_report._session + assert session1 != session2 +def test_analytics_admin_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AnalyticsAdminServiceGrpcTransport( + 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_analytics_admin_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AnalyticsAdminServiceGrpcAsyncIOTransport( + 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.AnalyticsAdminServiceGrpcTransport, transports.AnalyticsAdminServiceGrpcAsyncIOTransport]) +def test_analytics_admin_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.AnalyticsAdminServiceGrpcTransport, transports.AnalyticsAdminServiceGrpcAsyncIOTransport]) +def test_analytics_admin_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_account_path(): + account = "squid" + expected = "accounts/{account}".format(account=account, ) + actual = AnalyticsAdminServiceClient.account_path(account) + assert expected == actual + + +def test_parse_account_path(): + expected = { + "account": "clam", + } + path = AnalyticsAdminServiceClient.account_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_account_path(path) + assert expected == actual + +def test_account_summary_path(): + account_summary = "whelk" + expected = "accountSummaries/{account_summary}".format(account_summary=account_summary, ) + actual = AnalyticsAdminServiceClient.account_summary_path(account_summary) + assert expected == actual + + +def test_parse_account_summary_path(): + expected = { + "account_summary": "octopus", + } + path = AnalyticsAdminServiceClient.account_summary_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_account_summary_path(path) + assert expected == actual + +def test_conversion_event_path(): + property = "oyster" + conversion_event = "nudibranch" + expected = "properties/{property}/conversionEvents/{conversion_event}".format(property=property, conversion_event=conversion_event, ) + actual = AnalyticsAdminServiceClient.conversion_event_path(property, conversion_event) + assert expected == actual + + +def test_parse_conversion_event_path(): + expected = { + "property": "cuttlefish", + "conversion_event": "mussel", + } + path = AnalyticsAdminServiceClient.conversion_event_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_conversion_event_path(path) + assert expected == actual + +def test_custom_dimension_path(): + property = "winkle" + custom_dimension = "nautilus" + expected = "properties/{property}/customDimensions/{custom_dimension}".format(property=property, custom_dimension=custom_dimension, ) + actual = AnalyticsAdminServiceClient.custom_dimension_path(property, custom_dimension) + assert expected == actual + + +def test_parse_custom_dimension_path(): + expected = { + "property": "scallop", + "custom_dimension": "abalone", + } + path = AnalyticsAdminServiceClient.custom_dimension_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_custom_dimension_path(path) + assert expected == actual + +def test_custom_metric_path(): + property = "squid" + custom_metric = "clam" + expected = "properties/{property}/customMetrics/{custom_metric}".format(property=property, custom_metric=custom_metric, ) + actual = AnalyticsAdminServiceClient.custom_metric_path(property, custom_metric) + assert expected == actual + + +def test_parse_custom_metric_path(): + expected = { + "property": "whelk", + "custom_metric": "octopus", + } + path = AnalyticsAdminServiceClient.custom_metric_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_custom_metric_path(path) + assert expected == actual + +def test_data_retention_settings_path(): + property = "oyster" + expected = "properties/{property}/dataRetentionSettings".format(property=property, ) + actual = AnalyticsAdminServiceClient.data_retention_settings_path(property) + assert expected == actual + + +def test_parse_data_retention_settings_path(): + expected = { + "property": "nudibranch", + } + path = AnalyticsAdminServiceClient.data_retention_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_data_retention_settings_path(path) + assert expected == actual + +def test_data_sharing_settings_path(): + account = "cuttlefish" + expected = "accounts/{account}/dataSharingSettings".format(account=account, ) + actual = AnalyticsAdminServiceClient.data_sharing_settings_path(account) + assert expected == actual + + +def test_parse_data_sharing_settings_path(): + expected = { + "account": "mussel", + } + path = AnalyticsAdminServiceClient.data_sharing_settings_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_data_sharing_settings_path(path) + assert expected == actual + +def test_data_stream_path(): + property = "winkle" + data_stream = "nautilus" + expected = "properties/{property}/dataStreams/{data_stream}".format(property=property, data_stream=data_stream, ) + actual = AnalyticsAdminServiceClient.data_stream_path(property, data_stream) + assert expected == actual + + +def test_parse_data_stream_path(): + expected = { + "property": "scallop", + "data_stream": "abalone", + } + path = AnalyticsAdminServiceClient.data_stream_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_data_stream_path(path) + assert expected == actual + +def test_firebase_link_path(): + property = "squid" + firebase_link = "clam" + expected = "properties/{property}/firebaseLinks/{firebase_link}".format(property=property, firebase_link=firebase_link, ) + actual = AnalyticsAdminServiceClient.firebase_link_path(property, firebase_link) + assert expected == actual + + +def test_parse_firebase_link_path(): + expected = { + "property": "whelk", + "firebase_link": "octopus", + } + path = AnalyticsAdminServiceClient.firebase_link_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_firebase_link_path(path) + assert expected == actual + +def test_google_ads_link_path(): + property = "oyster" + google_ads_link = "nudibranch" + expected = "properties/{property}/googleAdsLinks/{google_ads_link}".format(property=property, google_ads_link=google_ads_link, ) + actual = AnalyticsAdminServiceClient.google_ads_link_path(property, google_ads_link) + assert expected == actual + + +def test_parse_google_ads_link_path(): + expected = { + "property": "cuttlefish", + "google_ads_link": "mussel", + } + path = AnalyticsAdminServiceClient.google_ads_link_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_google_ads_link_path(path) + assert expected == actual + +def test_key_event_path(): + property = "winkle" + key_event = "nautilus" + expected = "properties/{property}/keyEvents/{key_event}".format(property=property, key_event=key_event, ) + actual = AnalyticsAdminServiceClient.key_event_path(property, key_event) + assert expected == actual + + +def test_parse_key_event_path(): + expected = { + "property": "scallop", + "key_event": "abalone", + } + path = AnalyticsAdminServiceClient.key_event_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_key_event_path(path) + assert expected == actual + +def test_measurement_protocol_secret_path(): + property = "squid" + data_stream = "clam" + measurement_protocol_secret = "whelk" + expected = "properties/{property}/dataStreams/{data_stream}/measurementProtocolSecrets/{measurement_protocol_secret}".format(property=property, data_stream=data_stream, measurement_protocol_secret=measurement_protocol_secret, ) + actual = AnalyticsAdminServiceClient.measurement_protocol_secret_path(property, data_stream, measurement_protocol_secret) + assert expected == actual + + +def test_parse_measurement_protocol_secret_path(): + expected = { + "property": "octopus", + "data_stream": "oyster", + "measurement_protocol_secret": "nudibranch", + } + path = AnalyticsAdminServiceClient.measurement_protocol_secret_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_measurement_protocol_secret_path(path) + assert expected == actual + +def test_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AnalyticsAdminServiceClient.organization_path(organization) + assert expected == actual + + +def test_parse_organization_path(): + expected = { + "organization": "mussel", + } + path = AnalyticsAdminServiceClient.organization_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_organization_path(path) + assert expected == actual + +def test_property_path(): + property = "winkle" + expected = "properties/{property}".format(property=property, ) + actual = AnalyticsAdminServiceClient.property_path(property) + assert expected == actual + + +def test_parse_property_path(): + expected = { + "property": "nautilus", + } + path = AnalyticsAdminServiceClient.property_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_property_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AnalyticsAdminServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = AnalyticsAdminServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = AnalyticsAdminServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = AnalyticsAdminServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AnalyticsAdminServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = AnalyticsAdminServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = AnalyticsAdminServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = AnalyticsAdminServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AnalyticsAdminServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = AnalyticsAdminServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AnalyticsAdminServiceClient.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.AnalyticsAdminServiceTransport, '_prep_wrapped_messages') as prep: + client = AnalyticsAdminServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AnalyticsAdminServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AnalyticsAdminServiceClient.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 = AnalyticsAdminServiceAsyncClient( + 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 = AnalyticsAdminServiceClient( + 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 = AnalyticsAdminServiceClient( + 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", [ + (AnalyticsAdminServiceClient, transports.AnalyticsAdminServiceGrpcTransport), + (AnalyticsAdminServiceAsyncClient, transports.AnalyticsAdminServiceGrpcAsyncIOTransport), +]) +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, + )